c算法

斐波那契

void main()
{
    int a[10]={1, 1}, i;
    for (i=2;i<=9;i++)   //这里需要注意,for循环虽然《=9, 还有个i++
    {
        a[i] = a[i-2] + a[i-1];
        printf("%d, %d\n", a[i-2], i-2);
//          printf("%d", i);

    }
}
View Code

 

 

冒泡算法

void main()
{
    int i[7] = {9, 2, 3, 1, 5, 4, 6}, j, k, a, l;
    for (j=0;j<=7;j++)
        {
            for (k=0;k<=7-j;k++)
                {
                    if (i[k]>i[k+1])
                    {
                        a= i[k];
                        i[k] = i[k+1];
                        i[k+1] = a;
                    }

                }
        }
    for (l=0;l<=6;l++)
        {
            printf("%d", i[l]);
        }
}
View Code

 

 

二分查找

标注知识点:

一个程序在编译运行的时候, 普通变量是存放在栈里面的
而static会是的变量存放在data里
整个内存主要分为四大区:   CODE(代码), DATA(数据区,变量常量等), STACK(栈), HEAP(程序员定义)

 

二分法就是在一批有序数据中查找某数

思路:

首先, 选择这批数中间位置的一个数与所查找比较, 是在所选前面还是后面

从而缩小范围的一半。

一次类推在缩小一半。

 

代码:

#define M 10

void main()
{
    static int a[M] = {-12, 0, 6, 16, 23, 56, 80, 100, 110, 115};
    int n, low, mid, high, found;
    low=0;
    high=M-1;
    found=0;
    printf("Input a number to be searched:\n");

    do
    {
        scanf("%d", &n);
    }while(n < a[0] || n > a[M-1]);

    while(low<=high)
    {
        mid=(low+high)/2;
        if(n==a[mid])
        {
            found=1;
            break;
        }/*找到,结束循环*/
        else if(n>a[mid])
        {
            low = mid + 1;
        }
        else
        {
            high = mid - 1;
        }

    }
    if (found==1)
    {
        printf("The index of %d is %d", n, mid);
    }
    else
    {
        printf("There is not %d", n);
    }
}
View Code

 

posted @ 2017-06-19 16:38  我当道士那儿些年  阅读(272)  评论(0编辑  收藏  举报