zoukankan      html  css  js  c++  java
  • 插入排序的递归和非递归代码

    #include <stdio.h>
    
    int binary_search(int* arr,int len, int key)
    {
        int start = 0, mid = 0, end = len;
        while(start <= end){
            mid = (start + end)/2;
            if(arr[mid] == key){
                return mid;
            }else if(arr[mid] < key){
                start = mid + 1;
            }else{
                end = mid - 1;
            }
        }
        return start;
    }
    
    int binary_search_re(int* arr, int start, int end, int key) 
    {
        if(start > end)
            return start;
        int mid = (start + end) / 2;
        if(arr[mid] == key){
            return mid;
        }else if(arr[mid] < key){
            return binary_search_re(arr, mid + 1, end, key);
        }else{
            return binary_search_re(arr,start, mid-1 , key);
        }
    }
    int bsort(int* arr, int len, int flag_re)
    {
        int i = 0,j = 0, k = 0, act_pos = 0, key = 0;
        printf("input arr list:    ");
        for(i = 0; i < len; i++){
            printf("%3d ", arr[i]);
        }
        printf("
    ");
        i = 0;
    
        for(i = 1; i < len; i++){
            key = arr[i];
            if(flag_re){
                act_pos = binary_search_re(arr, 0, i, key);
            }else{
                act_pos = binary_search(arr, i, key);
            }
            
            for(j = i; j > act_pos; j--){
                int tmp = arr[j - 1];
                arr[j - 1] = arr[j];
                arr[j] = tmp;
            }
            arr[act_pos] = key;
            printf("sort num index(%2d) act_pos(%d):", i, act_pos);
            for(k = 0; k < len; k++){
                printf("%3d ", arr[k]);
            }
            printf("
    ");
        }
        return 0;
    }
    
    int main(int argc, char** argv)
    {
        int i = 0;
        int array[21] = {30, 11, 71, 15, 9, 31, 12, 24, 18,10, 3,13, 14,33,80, 47,8,5,6,26};
        int array1[21] = {30, 11, 71, 15, 9, 31, 12, 24, 18,10, 3,13, 14,33,80, 47,8,5,6,26};
        bsort(array, 20, 0);
        for(i = 0; i<20; i++){
            printf("%3d ", array[i]);
        }
        printf("
    ");
    
        bsort(array1, 20, 1);
        for(i = 0; i<20; i++){
            printf("%3d ", array1[i]);
        }
        printf("
    ");
        return 0;
    
    }
  • 相关阅读:
    迈瑞医疗招聘-软件测试工程师
    软件自动化测试开发-3期开班啦
    luogu P2744 [USACO5.3]量取牛奶Milk Measuring
    luogu P2515 [HAOI2010]软件安装
    luogu P2423 双塔
    luogu P1651 塔
    luogu P1489 猫狗大战
    luogu P3092 [USACO13NOV]没有找零No Change
    luogu P3800 Power收集
    luogu P2949 [USACO09OPEN]工作调度Work Scheduling
  • 原文地址:https://www.cnblogs.com/chriszsy/p/9049582.html
Copyright © 2011-2022 走看看