码迷,mamicode.com
首页 > 编程语言 > 详细

C基础--冒泡排序和二分查找法

时间:2015-09-21 12:20:09      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

#define N    10
void init_arry(int a[], int n)
{
    int i;

    srand(time(NULL));
    for (i = 0; i < n; i++)
        a[i] = rand() % 100;
}
void show_arry(int a[], int n)
{
    int i;
    for (i = 0; i < n; i++)
        printf("%5d", a[i]);
    putchar(\n);
}
void swap(int *x, int *y)
{
    int tmp;        //int *tmp;
    tmp = *x;
    *x = *y;
    *y = tmp;
}
void bubble_sort(int a[], int n)
{
    int i, j;

    for (i = 0; i < n; i++)
        for (j = 0; j < n-i-1; j++)
            if (a[j] > a[j+1])
                swap(&a[j], &a[j+1]);
}
int search_r(int a[], int l, int r,int key)        //找到return 1,else return 0
{
    int mid;
    if (l > r)
        return 0;
    mid = (l+r) / 2;
    if (a[mid] > key)
        search_r(a, l, mid-1, key);
    else if (a[mid] < key)
        search_r(a, mid+1, r, key);
    else
        return 1;
}
int search(int a[], int l, int r, int key)
{
    int mid;
    while (l <= r)
    {
        mid = (l+r) / 2;

        if (a[mid] > key)
            r = mid - 1;
        else if (a[mid] < key)
            l = mid + 1;
        else 
            return 1;
    }
    return 0;
}
int main(void)
{
    int a[N];
    int num, res;

    init_arry(a, N);
    show_arry(a, N);
    scanf("%d", &num);
    bubble_sort(a, N);
    show_arry(a, N);
    //res = search_r(a, 0, N-1, num);
    res = search(a, 0, N-1, num);
    if (res)
        printf("find %d in arry\n", num);
    else
        printf("un find\n");

    return 0;
}

 

C基础--冒泡排序和二分查找法

标签:

原文地址:http://www.cnblogs.com/zhuyaguang/p/4825560.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!