iOS算法

2020-10-20  本文已影响0人  Li_Po
image.png
      //利用快排思想求中位数
      |2|4|6|8|
      //调用
        int list[9] = {12,3,10,8,6,7,11,13,9};
        int median = medianFind(list, 9);
        printf("the median is %d",median);
        
      //求一个无需数组的我中位数
    int medianFind(int a[],int len)
    {
        int low = 0;
        int high = len-1;
        
        int mid = (len-1)/2;
        int div = PartSort(a,low,high);
        
        while (div != mid) {
            if (mid<div) {
                //左半区查找
                div = PartSort(a,low,div-1);
            }else{
                //右半区查找
                div = PartSort(a,div+1,high);
            }
        }
        //找到了
        return a[mid];
    }

    //
    int PartSort(int a[],int start,int end){
        int low = start;
        int high = end;
        
        int key = a[end];
        while (low<high) {
            //左边找比key大的值
            while (low<high&& a[low]<=key) {
                ++low;
            }
            //右边找比key小的值
            while (low<high&& a[end]>=key) {
                --high;
            }
            //找到之后交换左右的值
            if (low<high) {
                int tmp = a[low];
                a[low] = a[high];
                a[high] = tmp;
            }
        }
        
        int tmp = a[high];
        a[high] = a[end];
        a[end] = tmp;
        
        return low;
    }
上一篇下一篇

猜你喜欢

热点阅读