Quick sorting and quick sorting algorithms
Quick Sorting Algorithm
1. algorithm ideas
Sort the input array a [I, j:
1) decomposition: the input array is divided into three parts: a [I, k-1], a [k], and a [k + 1, j]. so that the elements in a [I, k-1] are not greater than (or less than) a [k], and a [k + 1, j] are greater than (or not less) a [k];
2) recursive solution: Call the quick sorting algorithm recursively to sort each part;
2. Algorithm Implementation
template<class T>int Partition(T a[], int left, int right){ T x = a[left]; while(left < right){ while( a[right] >= x && left < right) right--; if(left < right) a[left++] = a[right]; while( a[left] <= x && left < right) left++; if(left < right) a[right--] = a[left]; } a[right] = x; return right;}template<class T>void QuickSort(T a[], int left, int right){ if(left < right){ int temp = Partition(a, left, right); QuickSort(a, left, temp - 1); QuickSort(a, temp + 1, right); }}
3. Algorithm Analysis
The best time complexity of the quick sorting algorithm is round (nlog (n). At this time, the benchmark obtained each time is exactly the middle value, and the average time complexity is round (nlog (n )). However, when the benchmark is at the extreme of data, such as the maximum or minimum value of this sort, it will increase the time complexity. In the worst case, the input data is just ordered, and the time complexity is second (n2 ).
4. Algorithm Improvement
You can change the benchmark to reduce the worst time complexity in a quick sorting algorithm. You can modify the baseline of the original quick rank to generate a random number r (left <= r <= right) before selecting the benchmark ), then, the data corresponding to the random number position is exchanged with the first data in the sorting order, which can effectively reduce the extreme situations in sorting.