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

C语言-数据结构(一)

时间:2015-07-15 12:49:42      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

1.冒泡排序

void sort(int list[], int n) {
     int i, j, temp;
     for (i = 0; i < n - 1; i++) {
         for (j = i; j < n; j++) {
             if (list[i] < list[j]) {
                 temp = list[i];
                 list[i] = list[j];
                 list[j] = temp;
             }
         }
     }
 }

2.二分查找

int binsearch(int *list, int search, int num) {
    int middle;
    int left = 0;
    int right = num - 1;

    while (left <= right) {
        middle = (left + right) / 2;
        if (list[middle] > search) {
            right = middle - 1;
        } else if (list[middle] == search) {
            return middle;
        } else {
            left = middle + 1;
        }
    }

    return -1;
}

递归版本

int binsearch(int *list, int search, int left, int right) {
    int middle;
    if (left <= right) {
        middle = (left + right) / 2;
        if (list[middle] > search) {
            return binsearch(list, search, left, middle - 1);
        } else if (list[middle] == search) {
            return middle;
        } else {
            return binsearch(list, search, middle + 1, right);
        }
    }
    return -1;
}

3.

C语言-数据结构(一)

标签:

原文地址:http://www.cnblogs.com/JohnABC/p/4647806.html

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