C语言中各种函数汇总(集合全部)持续更新

1.快速排序:

#include <stdio.h>

void sort(int a[], int left, int right)
{
    int i = left, x = a[left], j = right;
    if(left >= right) return;
    while(i < j)
    {
        while(i < j && a[j] >= x) j--;
        a[i] = a[j];
        while(i < j && a[i] <= x) i++;
        a[j] = a[i];
    }
    a[i] = x;
    sort(a, left, i - 1);
    sort(a, i+1, right);

}

2.二分查找:

#include <stdio.h>

int f(int a[], int lf, int ri, int x)
{
    int mid;
    while(lf <= ri)
    {
        mid = (lf + ri) / 2;

        if(a[mid] == x)
            return mid + 1;
        else if(a[mid] < x)
        {
            lf = mid + 1;
        }
        else if(a[mid] > x)
        {
            ri = mid - 1;
        }
    }
    return 0;
}

int f(int a[], int lf, int ri, int x)
{
    int mid;
    while(lf <= ri)
    {
        mid = (lf + ri) / 2;


        if(a[mid] == x)
            return mid + 1;
        else if(a[mid] < x)
        {
            lf = mid + 1;
        }
        else if(a[mid] > x)
        {


            ri = mid - 1;
        }
    }
    return 0;
}

3.创建链表:

struct node
{
    struct node *next;
    int data;
}*head;

struct node *creat(int n)
{
    int i;
    struct node *head, *p, *tail;
    head=(struct node*)malloc(sizeof(struct node));
    head ->next= NULL;
    tail = head;
    for(i = 0; i < n; i++)
    {
        p = (struct node*)malloc(sizeof(struct node));
        scanf("%d", &p->data);
        p -> next = NULL;
        tail -> next = p;
        tail = p;
    }
    return head;
};

4.输出链表:

void show (struct node *head)
{
    struct node *t;
    t = head -> next;
    while(t)
    {

        if(t -> next != NULL)printf("%d ", t -> data);
        else printf("%d\n", t -> data);
        t = t -> next;
   }

}

5.判断闰年:


int f(int y)
{
    if((y%400==0)||(y%4==0&&y%100!=0))
        return 1;
    return 0;
}

6.判断素数:

#include <stdio.h>
#include <math.h>
int f(int n)
{
    int i;
    if(n == 1)
        return 0;
    else
    {
        for(i = 2; i <= sqrt(n); i++)
        {
            if(n % i == 0)break;
        }
        if(i <= sqrt(n))
            return 0;
        else
            return 1;
    }
}

猜你喜欢

转载自blog.csdn.net/Allinone99/article/details/81331058
今日推荐