Algorithm series Notes 1 (sorting), algorithm series notes sorting
This document mainly records some classic sorting algorithms, these include Bubble sorting, Direct selection sorting, insert sorting, Merge Sorting, fast sorting, heap sorting, Hill sorting, bucket sorting, Count sorting, and base sorting. First, we will give the basic ideas of these sorting algorithms, then give the implementation code, and finally give the time complexity.
1: Bubble Sorting
Thoughts:
(1): compare two adjacent elements. If the following data is smaller than the preceding data, the two data locations are exchanged. In this way, after a traversal, the smallest element will be in The 0th position, which belongs to the "bubble ".
(2): repeat the first step... To the top of the array.
// Three methods for data exchange void swap (int & t1, int & t2) {int tmp = t1; t1 = t2; t2 = tmp ;}
<Pre name = "code" class = "cpp"> // use an exclusive or exchange void swap2 (int & a, int & B) {if (! = B) {// prevent swap2 (a, a) from switching itself a ^ = B; B ^ = a; a ^ = B ;}} void swap3 (int & a, int & B) {if (! = B) {a = a + B; B = a-B; a = a-B ;}}
# Include <iostream> using namespace std; // You can optimize the settings of monitoring record. When this record is not exchanged, the exit time complexity is n ^ 2 void swap (int & t1, int & t2) {int tmp = t1; t1 = t2; t2 = tmp ;} void bubbleSort (int r1 [], int n) {for (int I = 0; I <n; I ++) {for (int j = n-1; j> I; j --) {if (r1 [j] <r1 [J-1]) {swap (r1 [j], r1 [J-1]) ;}}} int main () {int a [10] = {6, 5,}; bubbleSort (a, 10); cout <"after Bubble Sorting :"; for (int I = 0; I <10; I ++) {cout <a [I] <"" ;}cout <endl; return 0 ;}
Time Complexity: O (n ^ 2) is a stable sorting algorithm.
Note: You can perform optimization settings to monitor the whistle. When no exchanges are made for this trip, the system exits.
2: Select sort directly
Thought: the first time from R [0] ~ Select the minimum value in R [n-1] and exchange it with R [0]. The second time is from R [1] ~ Select the minimum value in R [n-1], exchange with R [1],..., I from R [I-1] ~ Select the minimum value in R [n-1], exchange with R [I-1],... n-1 from R [N-2] ~ In R [n-1], the minimum value is selected and exchanged with R [N-2]. A sequence sorted by sort code from small to large is obtained through n-1 times in total.
Code:
# Include <iostream> using namespace std; // use a temporary variable to exchange void swap (int & a, int & B) {int tmp = a; a = B; B = tmp;} void display (int a [], int n) {for (int I = 0; I <n; I ++) {cout <a [I] <";}cout <endl;} void SelectSort (int a [], int n) {for (int I = 0; I <n-1; I ++) {int minIndex = I; int minElement = a [minIndex]; for (int j = I + 1; j <n; j ++) {if (a [j] <minElement) {minElement = a [j]; minIndex = j ;}} swap3 (a [I], a [minIndex]);} int main () {int a [10] = {6, 5,}; SelectSort (a, 10); display (a, 10 ); return 0 ;}
Time Complexity: O (n ^ 2 ). It is an unstable sorting algorithm.
3: insert sorting
Idea: (1) At the beginning, a [0] is a self-contained ordered zone, and a [1,... n-1] is an unordered zone. Make I = 1
(2) Make temp = a [I], j from I-1 to 0, if a [j]> temp then a [j + 1] = a [j], in this way, a [I] is merged into the current ordered Zone a [0 ,... The Order interval of a [0,. I] is formed in the I-1.
(3) I ++ repeats the second step until I = n-1. Sorting is completed.
InsertSort. h
#ifndef INSERTSORT#define INSERTSORT#include "sortAlg.h"class InsertSort:public SortAlg{public:InsertSort(int *is, const int &len):SortAlg(is, len){}void sort(){for(int i = 1; i < length; i++){int j = i-1, tmp = sortElement[i];while(sortElement[j] > tmp && j >= 0){sortElement[j+1] = sortElement[j];j--;}sortElement[j+1] = tmp;}}};#endif
The average time complexity is O (n ^ 2). If the sequence has been sorted, the maximum efficiency is O (n ). Is a stable sorting algorithm.
4: Merge Sorting
Thought: (1) If there is only one element, it is sorted and returned. (2) Merge and sort A [1 ,... N/2] And A [n/2 + 1 ,... N].
(1) Merge O (n) for two merged sequences ).
Code:
# Include <iostream> using namespace std; void mergeSort (int r1 [], int r2 [], int s, int m, int t) {int I = s, j = m + 1; int k = s; while (I <= m & j <= t) {if (r1 [I] <= r1 [j]) r2 [k ++] = r1 [I ++]; elser2 [k ++] = r1 [j ++];} if (I> m) {while (j <= t) r2 [k ++] = r1 [j ++];} if (j> t) {while (I <= m) r2 [k ++] = r1 [I ++] ;}for (int n = s; n <= t; n ++) {// note that this is essential for r1 [n] = r2 [n];} void merge (int r1 [], int r2 [], int s, int t) {if (s <t) {int m = (s + t)/2; merge (r1, r2, s, m ); // merge and sort A [1, n/2] merge (r1, r2, m + 1, t); // merge and sort A [n/2 + 1 ,, n] mergeSort (r1, r2, s, m, t); // merge two sorted subsequences} void display (int * a, int length) {for (int I = 0; I <length; I ++) {cout <a [I] <";}cout <endl ;}int main () {int r1 [10] = {3, 2, 5, 1, 7, 4, 9, 7, 8, 7}, r2 [10]; merge (r1, r2, 0, 9); display (r2, 10); return 0 ;}
Time Complexity: O (nlgn). It is a stable sorting algorithm.
5. Quick sorting
Idea: (1) an element is usually selected as the principal component x (usually the first element, while the Randomization fast sorting is to randomly select an element and then exchange it with the first element ). Place the elements smaller than x in array A on the left and those greater than or equal to x on the Right of array. <This step is usually divided into two methods: the number of pitfalls in the book, from both sides. Another method is to start from one side, and the code is also given>.
(2) sort the Left and Right subsequences quickly.
Code:
# Include <iostream> # include <ctime> using namespace std; void swap (int & t1, int & t2) {int tmp = t1; t1 = t2; t2 = tmp ;} // The Division Method in the MIT video performs int Partition (int r1 [], int p, int q) {int I = p, j = p + 1; int outer = r1 [p]; for (j = p + 1; j <= q; j ++) {if (r1 [j] <outer) {I ++; swap (r1 [I], r1 [j]) ;}} swap (r1 [I], r1 [p]); return I ;} // In the book, the partitioning method is used to divide the data from both sides and fill in the number and conquer method. The unstable Sorting Algorithm int Partition2 (int r1 [], int p, int q) {int I = p, j = q; int comment = r1 [p]; while (I <j) {while (j> I & r1 [j]> comment) j --; if (j> I) r1 [I ++] = r1 [j]; while (I <j & r1 [I] <distinct) I ++; if (I <j) r1 [j --] = r1 [I];} r1 [I] = random; return I ;} // random fast Sorting Algorithm int randomPartition (int r1 [], int p, int q) {srand (unsigned) time (0); int randInt = rand () % (q-p + 1) + p; // randomly select an element as the principal swap (r1 [p], r1 [randInt]); int I = p, j = p + 1; int partition = r1 [p]; for (j = p + 1; j <= q; j ++) {if (r1 [j] <strong) {I ++; swap (r1 [I], r1 [j]) ;}} swap (r1 [I], r1 [p]); return I;} void QuickSort (int r1 [], int p, int q) {if (p <q) {int m = Partition (r1, p, q); // int m = randomPartition (r1, p, q); QuickSort (r1, p m-1); QuickSort (r1, m + 1, q) ;}} int main () {int a [10] = {6, 5, 4, 7, 2, 4, 8, 5, 10}; cout <"Before sorting :"; for (int I = 0; I <10; I ++) {cout <a [I] <";}cout <endl; QuickSort (a, 0, 9); cout <"after fast sorting:"; for (int I = 0; I <10; I ++) {cout <a [I] <";}cout <endl; return 0 ;}
The average time complexity is O (nlgn ). When the sequence is ordered, this is the worst case. The time complexity is O (n ^ 2 ). Is an unstable sorting algorithm.
6: heap sorting
Heap sorting first needs to understand the Heap Storage, deletion, insertion and heap process (can refer to: http://blog.csdn.net/morewindows/article/details/6709644 ). The idea of heap sorting is to swap the root element of the established heap (small heap example) with the last element, and then heap the heap except the last element into a binary heap, in this way, the last element is the smallest element. Repeat this operation to obtain an array in descending order.
Code:
# Include <iostream> using namespace std; void display (int a [], int n) {for (int I = 0; I <n; I ++) {cout <a [I] <";}cout <endl;} void swap (int & a, int & B) {int tmp =; a = B; B = tmp;} // use an array to store the heap. The inserted element is equivalent to the heap void minHeapFixUp (int a [], int I) {int tmp = a [I]; int j = (I-1)/2; while (j> = 0 & I! = 0) {// No I! If (a [j] <= tmp) break; a [I] = a [j]; I = j; j = (I-1)/2; //-1/2 = 0} a [I] = tmp;} // Add the element void minHeapAddNumber (int a [], int n, int x) to the minimum heap) {a [n-1] = x; minHeapFixUp (a, n-1);} // Delete All The 0th elements, and place the last element in the position of the 0th elements for heap void minHeapFixDown (int a [], int I, int n) {// Delete the element int j = 2 * I + 1; int tmp = a [I]; while (j <n) {if (j + 1 <n & a [j + 1] <a [j]) j ++; if (tmp <= a [j]) break; a [I] = a [j]; I = j; j = j * 2 + 1;} a [I] = tmp ;} // Delete the number of void minHeapDeleteNumber (int a [], int n) {swap (a [0], a [n-1]); minHeapFixDown (a, 0, n-2);} // heap array build minimum heap void makeMinHeap (int a [], int n) {for (int I = n/2-1; I> = 0; I --) {minHeapFixDown (a, I, n) ;}// heap sorting void minHeapSortToDes (int a [], int n) {for (int I = n-1; i> 0; I --) {swap (a [0], a [I]); minHeapFixDown (a, 0, I) ;}} int main () {int a [11] = {9, 12, 17,30, 50, 20, 60, 65, 4, 19}; // create makeMinHeap (a, 10 ); display (a, 10); // Add the minHeapAddNumber (a, 11, 3); display (a, 11); // Delete the element // minHeapDeleteNumber (a, 11 ); // display (a, 11); // heap sorting minHeapSortToDes (a, 11); display (a, 11); return 0 ;}
The time complexity is O (nlgn ). Is an unstable sorting algorithm.
7: Hill sorting
Idea: first, divide the entire sequence of elements to be arranged into several sub-sequences (composed of elements separated by an increment) for direct insertion and sorting respectively, and then reduce the increment in sequence before sorting, when the elements in the entire sequence are basically ordered (the increment is small enough), directly insert and sort all the elements. Because the efficiency of direct insert sorting is very high when the elements are basically ordered (close to the best condition), the time efficiency of hill sorting is much higher than that of the first two methods.
The step size generally starts with n/2, and is halved each time until the last step is 1.
Code:
# Include <iostream> using namespace std; void ShellSort (int a [], int n) {for (int gap = n/2; gap> 0; gap --) {// step size for (int I = gap; I <n; I ++) {int temp = a [I]; int j = I-gap; while (j> = 0 & a [j]> temp) {// sort by direct insertion. a [j + gap] = a [j]; j-= gap ;} a [j + gap] = temp ;}} void display (int a [], int n) {for (int I = 0; I <n; I ++) {cout <a [I] <"" ;}cout <endl ;}int main () {int a [10] = {6, 5, 5, 10}; ShellSort (a, 10); display (a, 10); return 0 ;}
Generally, the time complexity depends on the step size. It is an unstable sorting between O (nlgn) and O (n ^ 2.
8: Sort buckets
Bucket sorting (sort) or the so-called box sorting is a sorting algorithm, working by dividing arrays into a limited number of buckets. Each bucket can be sorted individually (it is possible to use another sort algorithm or to continue to use the bucket sort in a progressive manner ). Bucket sorting is an inductive result of nest sorting. When the values in the array to be sorted are evenly distributed, the linear time (n) is used for Bucket sorting )). However, bucket sorting is not a comparative sorting, and is not affected by the lower limit of O (n log n.
For example .. n integers in the 1000] range A [1 .. n] sorting. You can set the bucket size to 10. Specifically, set Set B [1] to store [1 .. the integer of 10], which is a set of B [2] storage (10 .. 20] integer ,...... Set the integer of B [I] storage (I-1) * 10, I * 10], I = 100. A total of 100 buckets are available. Scan A [1. n] From start to end, and put each A [I] in the corresponding bucket B [j. Then sort the numbers in each of these 100 buckets. In this case, you can use bubble, select, or even fast sorting. Generally, any sorting method is acceptable. Finally, the numbers in each bucket are output sequentially, and the numbers in each bucket are output from small to large. In this way, a sequence of all numbers is obtained.
Suppose there are n numbers and m buckets. If the numbers are evenly distributed, there are n/m numbers on average in each bucket. If the numbers in each bucket are sorted quickly, the complexity of the entire algorithm is O (n + m * n/m * log (n/m )) = O (n + nlogn-nlogm)
From the above formula, when m is close to n, the complexity of Bucket sorting is close to O (n)
Of course, the above complexity calculation is based on the assumption that n numbers are evenly distributed. This assumption is very strong, and the results in practical applications are not so good. If all the numbers are in the same bucket, the sorting will degrade.
# Include <iostream> using namespace std; // The Division Method in the MIT video only performs int Partition (int r1 [], int p, int q) {int I = p, j = p + 1; int partition = r1 [p]; for (j = p + 1; j <= q; j ++) {if (r1 [j] <strong) {I ++; swap (r1 [I], r1 [j]) ;}} swap (r1 [I], r1 [p]); return I;} void QuickSort (int r1 [], int p, int q) {if (p <q) {int m = Partition (r1, p, q); // int m = randomPartition (r1, p, q); QuickSort (r1, p m-1); QuickSort (r1, m + 1, q) ;}} // The element in each bucket is an array and records the number of elements stored in the bucket. struct bucket {int node [10]; // It should be the size of the array to be sorted. Here we define it as 10 very limited to int count;}; void BucketSort (int r1 [], int n) {// The bucket size is 10 buckets * pBucket = new bucket [10]; // initialize the bucket for (int I = 0; I <10; I ++) {(pBucket + I)-> count = 0;} int maxNum = r1 [0], minNum = r1 [0]; for (int I = 1; I <n; I ++) {if (r1 [I]> maxNum) maxNum = r1 [I]; if (r1 [I] <minNum) minNum = r1 [I];} // put data in the bucket for (int I = 0; I <n; I ++) {int index = (r1 [I]-minNum) /(maxNum-minNum) * 9; (pBucket + index)-> node [(pBucket + index)-> count] = r1 [I]; (pBucket + index) -> count ++;} // sort each bucket quickly or other sorting methods int k = 0; for (int I = 0; I <10; I ++) {QuickSort (pBucket + I)-> node, 0, (pBucket + I)-> count-1); for (int j = 0; j <(pBucket + I) -> count; j ++) {r1 [k ++] = (pBucket + I)-> node [j] ;}} delete [] pBucket ;} void display (int a [], int n) {for (int I = 0; I <n; I ++) {cout <a [I] <"" ;}cout <endl ;}int main () {int a [10] = {6, 5, 5, 10}; BucketSort (a, 10); display (a, 10); return 0 ;}
Time complexity O (n), which is an unstable Sorting Algorithm
9: Count sorting and base number
These two sorting algorithms are both linear time sorting algorithms. Counting sorting requires assuming that the input data is an integer in a cell, which is a small number. The base sorting is generally used to process a wide range of data in a linear time.
Code for counting and sorting:
# Include <iostream> using namespace std; void CountSort (int r1 [], int c [], int n, int k, int r2 []) {for (int I = 0; I <k; I ++) c [I] = 0; for (int I = 0; I <n; I ++) c [r1 [I] ++; // count the number of times each element appears for (int I = 1; I <k; I ++) c [I] = c [I-1] + c [I]; // count the number of elements smaller than or equal to that, that is, the position of the element to be placed in r2 // for (int I = n-1; I> = 0; I --) {// to ensure the algorithm is stable for (int I = 0; I <n; I ++) {r2 [c [r1 [I]-1] = r1 [I]; c [r1 [I] = c [r1 [I]-1 ;}} int main () {int a [10] = {2, 3, 1, 4, 5, 2, 3}, B [10]; int c [6]; cout <"Before sorting:"; for (int I = 0; I <10; I ++) {cout <a [I] <"";} cout <endl; CountSort (a, c, 10, 6, B); cout <"after sorting:"; for (int I = 0; I <10; I ++) {cout <B [I] <"" ;}cout <endl; return 0 ;}
The base sorting code may be limited to practical applications. It can be sorted by bit, then to ten, and finally to a high level.
Their time complexity is O (n)
Conclusion: (1) Bubble sorting, Direct selection sorting, insert sorting, Merge Sorting, fast sorting, heap sorting, and Hill sorting are compared-based sorting algorithms, the average time complexity is no less than O (nlgn ). The counting and base sorting algorithms are linear time sorting algorithms. Bucket sorting is special
(2) the average time complexity of Bubble sorting, direct sorting, and insertion sorting is O (n ^ 2 ). The average time complexity of Merge Sorting, fast sorting, and heap sorting is O (nlgn), which is the best comparison Sorting Algorithm for progressive sorting. The bucket sorting, counting sorting, and base sorting are O (n)
(3) directly select sorting, fast sorting, heap sorting, Hill sorting (cross-step switching), and bucket sorting are all unstable sorting algorithms. All others are stable sorting algorithms.
References
1: http://blog.csdn.net/column/details/algorithm-easyword.htmlvernacular classic algorithm series
2: http://blog.csdn.net/houapple/article/details/6480100bucket sorting