选择,冒泡排序,折半查找,插入

#include <stdio.h>

void selectSort(int nums[], int length);
void bubbleSort(int nums[], int length);
int findKey(int num[], int len, int k);
int insertKey(int num[], int len, int k);

void print(int arr[], int len)
{
    for (int i = 0; i<len; i++) {
        printf("%d\t", arr[i]);
    }
    printf("\n");
}

int main(int argc, const char * argv[]) {
    // 选择排序
    int a[5] = {3, 2, 4, 1, 5};
    int len = sizeof(a) / sizeof(a[0]);
    print(a,len);
    selectSort(a, len);
    print(a,len);
    
    printf("----------------------\n");
    
    // 冒泡排序
    int b[5] = {3, 2, 4, 1, 5};
    int len2 = sizeof(b) / sizeof(b[0]);
    print(b,len2);
    bubbleSort(b, len2);
    print(b,len2);
    
    printf("----------------------\n");
    
    // 折半查找
    int nums[] = {1, 3, 5, 7, 9, 11};
    int key = 5;
    int length = sizeof(nums) / sizeof(nums[0]);
    int index = findKey(nums, length, key);
    if (index != -1) {
        printf("查找元素的索引为:index = %d\n", index);
    }else{
        printf("找不到该元素");
    }
    
    // 插入位置
    key = 6;
    int index2 = insertKey(nums, length, key);
    printf("key要插入的位置索引为:index = %d\n", index2);
    
    
    return 0;
}

// 交换两个元素的位置
void swip(int nums[], int i, int j)
{
    int temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
}

/** 选择排序 */
void selectSort(int nums[], int length)
{
    for (int i = 0; i < length - 1; i++) {
        for (int j = i + 1; j < length; j++) {
            if (nums[i] > nums[j]) {
                swip(nums, i, j);
            }
        }
    }
}

/** 冒泡排序 */
void bubbleSort(int nums[], int length)
{
    for (int i = 0; i < length; i++) {
        for (int j = 0; j < length - i - 1; j++) {
            if (nums[j] > nums[j+1]) {
                swip(nums, j, j+1);
            }
        }
    }
}

/** 
 *折半查找
 *
 *如果找到返回查找索引,没有找到返回-1
 */
//
int findKey(int num[], int len, int k)
{
    int min = 0, max = len - 1;
    int mid = (min + max) / 2;
    
    while (1) {
        
        if (min > max){
            return -1;
        }
        
        if (k == num[mid]) {
            return mid;
        }else if(k < num[mid]){
            max = mid - 1;
        }else{
            min = mid + 1;
        }
        
        mid = (min + max) / 2;
    }
}

/**
 插入位置
 */
int insertKey(int num[], int len, int k)
{
    int min = 0, max = len - 1;
    int mid = (min + max) / 2;
    
    while (min <= max) {
        if (k == num[mid]) {
            return mid;
        }else if(k < num[mid]){
            max = mid - 1;
        }else{
            min = mid + 1;
        }
        mid = (min + max) / 2;
    }
    
    return min;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

posted on 2015-10-20 21:40  ll_xyls  阅读(148)  评论(0编辑  收藏  举报