Introduction to algorithms-sorting (2) Fast sorting and randomization quick sorting

Source: Internet
Author: User

Introduction to algorithms-sorting (2) Fast sorting and randomization quick sorting
Directory 1. Introduction 2. Fast sorting 3. Random fast sorting 4. complete source code 5. reference content 1. This article mainly consists of two parts, analyze the algorithm efficiency in the case of the best, the worst, and the best and the worst alternation. The other part is to introduce the randomization algorithm and analyze its algorithm complexity. Finally, the c ++ implementation code is provided. 2. Fast sorting fast sorting is also based on the grouping idea. First, we divide the arrays to be sorted into two parts, and then sort the sub-arrays respectively. Recursion is introduced when the sub-array is one element, and sorting is completed. Quick sorting is an "in-situ sorting", that is, sorting in the original Array Memory without occupying other memory. Merge Sorting is different. It requires additional space for Merge Sorting. It is the idea of division and governance of fast sorting: the most important step in fast sorting is the step of differentiation, which is the core of the algorithm's processing problem. Therefore, we can regard quick sorting as recursively dividing arrays, just as merging and sorting is recursively merging arrays. There are several specific algorithms for Paritition. Their pseudo code is slightly different, but their principles are the same. Of course, the most important thing is that the complexity of the Partition algorithm is linear, that is, O (n ). The following is A pseudo code of Partition: Copy code 1 Partition (A, p, q) 2 x <-A [p] // select the first primary key 3 I <-p4 for j <-p + 1 to q5 do if A [j] <x // less put the data of the principal component on the left 6 then I <-I + 17 exch A [I] <-> A [j] // exchange A [I] A [j] 8 exch [p] <-> A [I] // exchange 9 return I // after the return is divided, the primary key index copies the code and then it is simple recursion, the following is the pseudo code of the fast sorting: 1 QuickSort (A, p, q) 2 if p <q // if it is not true, we will introduce recursion 3 then r <-Partition (A, p, q) // sharding 4 QuickSort (A, p, R-1) // recursive fast row left sub array 5 QuickSort (A, r + 1, q) // recursive fast-forward right sub-array next analysis fast-forward Algorithm Efficiency 1) worst case analysis: when the input sequence is in positive or reverse order, the efficiency is the worst. In this case, the efficiency is n2. 2) under optimal conditions, the efficiency of other algorithms tends to be optimized (nlgn). So how can we ensure that our efficiency is always in optimal conditions? This is the problem that needs to be solved in randomization and quick sorting. 3. We already know that the input itself has been sorted by randomization, Which is worse for fast sorting. So how can we avoid this situation? One method is used to randomly arrange the elements in the sequence, and the other method is used to randomly select the principal component ). This is the idea of randomizing fast sorting. The advantage of this fast sorting is that its running time does not depend on the order of input sequences. According to the analysis, the efficiency of the Randomization fast sorting algorithm is lift (nlgn ). Implementation: we only need to add a random factor when selecting the primary element. Similar to the fast sorting, the following is the Partition programming (c ++) to implement 1 int Random_Partition (vector <T> & A, int p, int q) 2 {3 int I = rand () % (q-p) + p; // This row is different from the fast rank. Add the random number parameter 4swap (A [I], A [p]); // This line is different from the fast sorting, and the 5 return Partition (A, p, q) is randomly selected ); // This is the same as the Quick Sort 6} copy the code // randomize the Quick Sort 1 void Random_Quick_Sort (vector <T> & A, int p, int q) 2 {3 if (p <q) 4 {5 int I = Random_Partition (A, p, q); 6 Random_Quick_Sort (A, p, I-1); 7 Random_Quick_Sort (, I + 1, q); 8} 9} copy the Code 4. The complete source code contains the source code discussed earlier Insert and merge sorting algorithms. Finally, the time comparison is provided. h (implementation of the header file in the test room, do not understand, do not need to tangle) 1 # ifndef CTIMER_HH 2 # define CTIMER_HH 3 class CTimer 4 {5 public: 6 CTimer () 7 {8 QueryPerformanceFrequency (& m_Frequency); 9 Start (); 10} 11 void Start () 12 {13 QueryPerformanceCounter (& m_StartCount); 14} 15 double End () 16 {17 LARGE_INTEGER CurrentCount; 18 QueryPerformanceCounter (& CurrentCount); 19 return double (CurrentCount. lowPart-m_StartCount.LowPart) * 1000/(double) m_Frequency.LowPart; 20} 21 void ShowNow () 22 {23 LARGE_INTEGER CurrentCount; 24 QueryPerformanceCounter (& CurrentCount ); 25 cout <"Timer Count is:" <double (CurrentCount. lowPart-m_StartCount.LowPart) * 1000/(double) m_Frequency.LowPart <endl; 26} 27 private: 28 LARGE_INTEGER m_Frequency; 29 LARGE_INTEGER m_StartCount; 30}; 31 # endif copy code Sort. h (the Sorting Algorithm [insert sorting, Merge Sorting, fast sorting, and randomization quick sorting] implements the header file) copy code 1 # ifndef SORT_HH 2 # define SORT_HH 3 template <typename T> // With template 4 class Sort 5 {6 public: 7 void insertion_sort (vector <T> & ); // insert sort 8 void merge_sort (vector <T> & A, int p, int r); // merge sort 9 void print_element (vector <T> ); // print the array 10 void Quick_Sort (vector <T> & A, int p, int q); // fast sorting 11 int Partition (vector <T> & A, int p, int q); // 12 void Swap (T & m, T & n); // exchange data 13 void Random_Quick_Sort (vector <T> & A, int p, int q); // random fast sorting 14 int Random_Partition (vector <T> & A, int p, int q); // random partitioning 15 private: 16 void merge (vector <T> & A, int p, int q, int r); // merge sort subroutine 17 }; 18 template <typename T> // insert Sort 19 void Sort <T>: insertion_sort (vector <T> & A) 20 {21 int I, j; 22 T key; 23 int len =. size (); 24 for (j = 1; j <len; j ++) 25 {26 I = J-1; 27 key = A [j]; 28 while (I> = 0 & A [I]> key) 29 {30 A [I + 1] = A [I]; 31 I --; 32} 33 A [I + 1] = key; 34} 35} 36 37 template <typename T> // merge Sort subroutine 38 void Sort <T> :: merge (vector <T> & A, int p, int q, int r) 39 {40 int n1 = q-p + 1; 41 int n2 = r-q; 42 T * L = new T [n1 + 1]; 43 T * R = new T [n2 + 1]; 44 45 for (int I = 0; I <n1; I ++) 46 L [I] = A [I + p]; 47 for (int I = 0; I <n2; I ++) 48 R [I] = A [I + q + 1]; 49 50 L [n1] = R [n2] = INT_MAX; 51 52 int I = 0, j = 0; 53 for (int k = p; k <= r; k ++) 54 {55 if (L [I]> R [j]) 56 {57 A [k] = R [j]; 58 j ++; 59} 60 else 61 {62 A [k] = L [I]; 63 I ++; 64} 65} 66 67 delete [] L; 68 delete [] R; 69 70} 71 72 template <typename T> // merge Sort 73 void Sort <T> :: merge_sort (vector <T> & A, int p, int r) 74 {75 if (p <r) 76 {77 int mid = (p + r)/2; 78 merge_sort (A, p, mid); 79 merge_sort (A, mid + 1, r); 80 merge (A, p, mid, r ); 81} 82} 83 84 template <typename T> // exchange data 85 void Sort <T>: Swap (T & m, T & n) 86 {87 T tmp; 88 tmp = m; 89 m = n; 90 n = tmp; 91} 92 93/************ fast sorting and partitioning program *************/94 template <typename T> 95 int Sort <T>:: Partition (vector <T> & A, int p, int q) 96 {97 T x = A [p]; 98 int I = p; 99 for (int j = p + 1; j <= q; j ++) 100 {101 if (A [j] <x) 102 {103 I = I + 1; 104 Swap (A [I], A [j]); 105} 106} 107 Swap (A [p], A [I]); 108 return I; 109} 110 template <typename T> // fast sorting 111 void Sort <T>: Quick_Sort (vector <T> & A, int p, int q) 112 {113 if (p <q) 114 {115 int I = Partition (A, p, q); 116 Quick_Sort (A, p, I-1); 117 Quick_Sort (, I + 1, q); 118} 119} 120 121 template <typename T> // randomization fast sorting and partitioning program 122 int Sort <T> :: random_Partition (vector <T> & A, int p, int q) 123 {124 int I = rand () % (q-p) + p; 125 Swap (A [I], A [p]); 126 return Partition (A, p, q ); 127} 128 129 template <typename T> // random fast sorting 130 void Sort <T>: Random_Quick_Sort (vector <T> & A, int p, int q) 131 {132 if (p <q) 133 {134 int I = Random_Partition (A, p, q); 135 Random_Quick_Sort (A, p, I-1); 136 Random_Quick_Sort (, I + 1, q); 137} 138} 139 140 template <typename T> // print the array 141 void Sort <T >:: print_element (vector <T>) 142 {143 int len =. size (); 144 for (int I = 0; I <len; I ++) 145 {146 std: cout <A [I] <""; 147} 148 std: cout <std: endl; 149} 150 # endif copy the code Sort_main.cpp (test the main program) copy code 1 # include <iostream> 2 # include <vector> 3 # include <time. h> 4 # include <Windows. h> 5 using namespace std; 6 # include "Sort. h "7 # include" CTimer. h "8 9 # define N 10 // sorting array size 10 // Random parameter sorting array 11 void Random (vector <int> & a, int n) 12 {13 int I = 0; 14 srand (unsigned) time (NULL); 15 while (I <n) 16 {17 a [I ++] = rand (); 18} 19} 20 int main () 21 {22 Sort <int> sort1; 23 CTimer t; 24 vector <int> vec_int (N); 25 Random (vec_int, N); 26 cout <"source array:"; 27 sort1.print _ element (vec_int); 28 t. start (); 29 sort1.Quick _ Sort (vec_int, 0, vec_int.size ()-1); 30 cout <"Quick Sort:" <t. end () <"ms" <endl; 31 sort1.print _ element (vec_int); 32 Random (vec_int, N); 33 t. start (); 34 sort1.Random _ Quick_Sort (vec_int, 0, vec_int.size ()-1); 35 cout <"randomize fast sorting:" <t. end () <"ms" <endl; 36 sort1.print _ element (vec_int); 37 Random (vec_int, N); 38 t. start (); 39 sort1.insertion _ sort (vec_int); 40 cout <"insert sort:" <t. end () <"ms" <endl; 41 sort1.print _ element (vec_int); 42 Random (vec_int, N); 43 t. start (); 44 sort1.merge _ sort (vec_int, 0, vec_int.size ()-1); 45 cout <"merge sort:" <t. end () <"ms" <endl; 46 sort1.print _ element (vec_int); 47 48 system ("PAUSE"); 49 return 0; 50}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.