《算法导论》学习总结 — 9.第九章 中位数和顺序统计学


http://mindlee.net/2011/08/03/median-and-order-statistics/
四种快速排序
http://www.wutianqi.com/http:/www.wutianqi.com/?p=2395
第i个顺序统计量:在一个由n个元素组成的集合中,第i个顺序统计量(order statistic)是该集合中第i小的元素。
最小值是第1个顺序统计量(i=1)
最大值是第n个顺序统计量(i=n)
中位数:一个中位数(median)是它所在集合的“中点元素”,当n为奇数时,i=(n+1)/2,当n为偶数是,中位数总是出现在1 (下中位数)和2 (上中位数)。
如果要同时找出最大值和最小值,则比较次数最少并不是2*n-2,而是3 ,我们可以将一对元素比较,然后把较大者于max比较,较小者与min比较,这样就只需要3 。
如果是一般的选择问题,即找出一段序列第i小的数,看起来要比找最大值或最小值要麻烦,其实两种问题的渐进时间都是4 。
该算法的平均情况性能较好,并且又是随机化的,所有没有哪一种特别的输入会导致最坏情况发生。
 这种算法,利用“快排的或者类似二分”的思想,每次以枢纽为界,分两边,每次只需处理一边即可(抛弃另一边),平均情况下的运行时间界为O(n),这种算法以期望时间做选择。《算法都论》里是,在分治时用随机数来选取枢纽(算法导论中伪代码见图),好吧,这是理论上的算法,它没有考虑实际产生随机数的开销,事实上,效率一点也不高,已经测试过,产生随机数花费的开销真的很大,后边我用更快的三数中值又实现了一遍,思想是一样的,只是效率提高了。
3、 第三种算法以最坏情况线性时间做选择,最坏运行时间为O(n),这种算法基本思想是保证每个数组的划分都是一个好的划分,以5为基,五数取分,这个算法,算法导论没有提供伪代码,额,利用它的思想,可以快速返回和最终中位数相差不超过2的数,这样的划分接近最优,基本每次都二分了(算法导论中步骤见图)
int Partition(int kp[], int low, int high) {
    int pivotkey = kp[high];
    int i =  low - 1;
    for (int j = low; j < high; j++) {
        if (kp[j] <= pivotkey) {
            i++;
            swap(kp[j], kp[i]);
        }
    }
    swap(kp[i + 1], kp[high]);
    return i + 1;
}//Partition
inline int Random(int low, int high) {
    return (rand() % (high - low + 1)) + low;
}
int Randomized_Partition(int kp[], int low, int high) {
     int i = Random(low, high);
     swap(kp[low], kp[i]);
     return Partition(kp, low, high);
}
  
int  Randomized_Select(int kp[], int low, int high, int k) {
    if (low == high) {
        return kp[low];
    }
    int pivotloc =  Randomized_Partition(kp, low, high) ;
    int num = pivotloc - low + 1;//小于等于枢纽,数的个数
    if (num == k) return kp[pivotloc];
    if (k < num) {
        return Randomized_Select(kp, low, pivotloc - 1, k);
    } else {
        return Randomized_Select(kp, pivotloc + 1, high, k - num);
    }
}
第二种:以期望线性时间做选择,三数中值选取枢纽元
int Median(int kp[], int low, int high) {
    int center = (low + high) >> 1;
    if (kp[low] > kp[center]) swap(kp[low], kp[center]);
    if (kp[low] > kp[high]) swap(kp[low], kp[high]);
    if (kp[center] > kp[high]) swap(kp[center], kp[high]);
    swap(kp[center], kp[high - 1]);//枢纽放到了kp[high - 1]
    return kp[high - 1];
}
//下边是我的解法:三数取中求第k小数
int Qselect1(int kp[], int low, int high, int k) {
    if (low + 2 <= high) {
        int pivotloc = Median(kp, low, high);
        int i = low, j = high - 1;
        for (; ;) {
            while (kp[++i] < pivotloc) {}
            while (kp[--j] > pivotloc) {}
            if (i < j)  swap(kp[i], kp[j]);
            else break;
        }
        swap(kp[i], kp[high - 1]);
         
        int num = i - low + 1;
        if (k == num) return kp[i];
        if (k < num) {
            return Qselect1(kp, low, i - 1, k);
        } else {
            return Qselect1(kp, i + 1, high, k - num);
        }
    } else {//上边的三数取中不能处理两个元素的情况,下边单独处理
        if (high == low) {//一个元素情况
            return kp[low];
        }
        if (high - low == 1) {//两个元素情况
            if (kp[low] > kp[high]) swap(kp[low], kp[high]);
            if (k == 1) return kp[low];
            return kp[high];
        }
    }
}//Qselect1
   
//插入排序
void InsertionSort(int kp[], int n) {
    for (int j, i = 1; i < n; i++) {
        int tmp = kp[i];
        for (j = i; j > 0 && kp[j - 1] > tmp; j--) {
            kp[j] = kp[j - 1];
        }
        kp[j] = tmp;
    }
}
//后来才发现《数据结构与算法分析》理有三数取中求第k小的代码
//不过我写的和它还是有些不一样…… 下边是它的版本 (后来加)
void Qselect2(int kp[], int low, int high, int k) {
    if (low + 3 <= high) {
        int pivotloc = Median(kp, low, high);
        int i = low, j = high - 1;
        for (; ;) {
            while (kp[++i] < pivotloc) {}
            while (kp[--j] > pivotloc) {}
            if (i < j)  swap(kp[i], kp[j]);
            else break;
        }
        swap(kp[i], kp[high - 1]);
         
        if (k <= i) {
            return Qselect2(kp, low, i - 1, k);
        } else if (k > i + 1) {
            return Qselect2(kp, i + 1, high, k);
        }
    } else {
         InsertionSort(kp + low, high - low + 1);
    }
}//Qselect2
/*利用中位数来选取枢纽元,这种方法最坏情况下运行时间是O(n)
 这里求的中位数是下中位数
算法导论里没有伪代码,写起来很麻烦
注意这里的查找到的中位数,并不是真正意义上的中位数
而是和真正中位数相差不超过2的一个数
开始以为我写错了,又看了算法导论,应该就是这个意思
返回的是[x - 1, x + 2]的一个数,中位数是x
从下边的输出中也可以看出:
*/
const int maxn = 14;//kp -> size
const int maxm = maxn / 5 + 1;//mid -> size
int kp[maxn];
int mid[maxm];
//插入排序
void InsertionSort(int kp[], int n) {
    for (int j, i = 1; i < n; i++) {
        int tmp = kp[i];
        for (j = i; j > 0 && kp[j - 1] > tmp; j--) {
            kp[j] = kp[j - 1];
        }
        kp[j] = tmp;
    }
}
//查找中位数, 保证每一个划分都是好的划分
 int FindMedian(int kp[], int low, int high) {
     if (low == high) {
         return kp[low];
     }
     int index = low;//index初始化为low
      
     //如果本身小于5个元素,这一步就跳过
     if (high - low + 1 >= 5) {
         //储存中位数到mid[]
         for (index = low; index <= high - 4; index += 5) {
             InsertionSort(kp + index, 5);
             int num = index - low;
             mid[num / 5] = kp[index + 2];
         }
     }
     //处理剩下不足5个的元素
     int remain = high - index + 1;
     if (remain > 0) {
         InsertionSort(kp + index, remain);
         int num = index - low;
         mid[num / 5] = kp[index + (remain >> 1)];//下中位数
     }
      
     int cnt = (high - low + 1) / 5;
     if ((high - low + 1) % 5 == 0) {
         cnt--;//下标是从0开始,所以需要-1
     }//存放在[0…tmp]
      
     if (cnt == 0) {
         return mid[0];
     } else {
         return FindMedian(mid, 0, cnt);
     }
 }
   
int Qselect(int kp[], int low, int high, int k) {
    int pivotloc = FindMedian(kp, low, high);
    //这里有点不一样,因为不知道pivotloc下标,所以全部都要比较 
    int i = low - 1, j = high + 1;
    for (; ;) {
        while (kp[++i] < pivotloc) {}
        while (kp[--j] > pivotloc) {}
        if (i < j)  swap(kp[i], kp[j]);
        else break;
    }
    int num = i - low + 1;
    if (k == num) return kp[i];
    if (k < num) {
        return Qselect(kp, low, i - 1, k);
    } else {
        return Qselect(kp, i + 1, high, k - num);
    }
}

快速排序优化

2、由于N <= 20时,插入排序效率高于快速排序,于是就可以想在快排到递归时,当n <= 20,采用插入排序
当n > 20时,采用快排,这种方法效率可以提高很多.

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts