1. 程式人生 > >演算法筆記-快速排序之無序陣列中查詢中位數

演算法筆記-快速排序之無序陣列中查詢中位數

問題描述:

給一個無序陣列array和陣列長度n,找出其中的中位數(這裡考慮n為奇數)

Sample:

 ***** Input:
 ***** @[@(500),@(120),@(7),@(220),@(3),@(8),@(4),@(200),@(100)
 ***** Output:
 ***** 100
解法一:將陣列進行排序,然後輸出array(n-1)/2,排序演算法中我們選取快速排序:
- (void)quickSortingWitharray:(NSMutableArray *)array andleftIndex:(NSInteger)left withRightIndex:(NSInteger)right
{ if (left >= right) { return; } NSInteger leftIndex = left; NSInteger rightIndex = right; NSInteger key = [array[left] integerValue]; while (leftIndex < rightIndex) { while ([array[rightIndex] integerValue] >= key && leftIndex < rightIndex) { rightIndex --; } array
[leftIndex] = array[rightIndex]; while ([array[leftIndex] integerValue] <= key && leftIndex < rightIndex) { leftIndex ++; } array[rightIndex] = array[leftIndex]; } array[leftIndex] = @(key); [self quickSortingWitharray:array andleftIndex:left
withRightIndex:leftIndex - 1]; [self quickSortingWitharray:array andleftIndex:leftIndex + 1 withRightIndex:right]; }
解法二:還是用快速排序,但是我們可以減少一部分排序,因為每次快排都是將陣列分成左右兩個小陣列再進行排序,我們知道右邊的陣列中的值都是大於左邊陣列中的值,而且我們可以獲取到每次分組時的位置index,index和(n-1)/2,做比較,當相等時,array[index]就找到了我們要的值

- (NSInteger)yquickSortingWitharray:(NSMutableArray *)array andleftIndex:(NSInteger)left withRightIndex:(NSInteger)right{

    NSInteger leftIndex = left;
    NSInteger rightIndex = right;
    NSInteger key = [array[left] integerValue];

    while (leftIndex < rightIndex) {

        while ([array[rightIndex] integerValue] >= key && leftIndex < rightIndex) {
            rightIndex --;
        }
        array[leftIndex] = array[rightIndex];


        while ([array[leftIndex] integerValue] <= key && leftIndex < rightIndex) {
            leftIndex ++;
        }
        array[rightIndex] = array[leftIndex];
    }

    array[leftIndex] = @(key);

    return leftIndex;


}

- (NSInteger)finmidArray:(NSMutableArray *)array {
    NSInteger mid = (array.count-1)/2;
    NSInteger start = 0;
    NSInteger end = array.count - 1;

    NSInteger index = [self yquickSortingWitharray:array andleftIndex:start withRightIndex:end];
    while (index != mid) {
        if (mid < index) {
            index = [self yquickSortingWitharray:array andleftIndex:start withRightIndex:index - 1];
        } else {
            index = [self yquickSortingWitharray:array andleftIndex:index + 1 withRightIndex:end];
        }
    }

    return [array[index] integerValue];
}
  • 通過下圖我們可以看到通過解法二,可以省略很多次排序也可以拿到中位數100.
    解法二我們拿到中位數時的陣列