Sorted classification
(1) Internal sorting method: all data to be processed are i loaded into internal memory for sorting.
(2) External sorting method: the amount of data is too large to be loaded into memory. It needs to be sorted with the help of external storage (files, etc.).
Time complexity of the algorithm
Two methods to measure the execution time of a program (algorithm)
(1) Post statistical method
This method is feasible, but there are two problems: first, if you want to evaluate the new performance of the designed algorithm, you need to actually run the program; Second, the statistics of the obtained time depend on the computer's hardware, software and other environmental factors. In this way, if the same computer runs in the same state, it can be compared with the bolt hair familiar reading.
(2) Method of ex ante estimation
By analyzing the time complexity of an algorithm, we can judge which algorithm is better
Common time complexity
1) Constant order O (1)
2) Logarithmic order O (log2n)
3) Linear order O (n)
4) Linear logarithmic order O (nlog2n)
5) Square order O(n^2) 6) cubic order O(n^3)
7) K-th order O(n^k) 8) exponential order O(2^n)
The time complexity of common algorithms from small to large is: O (1) < o (log2n) < o (n) < o (nlog2n) < o (n ^ 2) < o (n ^ 3) < o (n ^ k) < o (2 ^ n)
Average time complexity and worst time complexity
Sorting method | average time | Worst case | Stability | Extra space | remarks |
---|---|---|---|---|---|
Bubbling | O(n^2) | O(n^2) | stable | O(1) | n small is better |
exchange | O(n^2) | O(n^2) | instable | O(1) | n small is better |
choice | O(^2) | O(n^2) | instable | Small O(1)n is better | |
insert | O(n^2) | O(n^2) | stable | O(1) | Better when most are sorted |
base | O(logRB) | O(logRB) | stable | O(n) | B is the true number (0-9), and R is the cardinal number (ten hundred) |
Shell (Hill) | O(nlogn) | O(n^s)1 < s< 2 | instable | O(1) | s is the selected group |
fast | O(nlogn) | O(n^2) | instable | O(nlogn) | n large is better |
Merge | O(nlogn) | O(nlogn) | stable | O(1) | n large is better |
heap | O(nlogn) | O(nlogn) | instable | O(1) | n large is better |
Bubble sorting
Bubble sort
Basic idea of Sorting: by comparing the values of adjacent elements from front to back (starting from the elements with smaller subscripts) in the sequence to be sorted, if the reverse order is found, exchange, so that the elements with larger values gradually move from front to back.
Algorithm steps:
Compare adjacent elements. If the first one is bigger than the second, exchange them.
Do the same for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. After this step, the last element will be the maximum number.
Repeat the above steps for all elements except the last one.
Continue to repeat the above steps for fewer and fewer elements at a time until no pair of numbers need to be compared.
Code implementation:
public static void main(String[] args) { //Create an array with a size of 8 and assign an initial value to it int[] arr = {1,8,2,5,7,4,3,9}; int length = arr.length; //Create variables to reduce unnecessary loops and time complexity boolean flag = false; //Sort from small to large for(int i = 1;i < length; i++) { flag = false; for(int j = 0;j < length-i;j++) { if(arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; flag = true; } } if(!flag) { break; } } }
Select sort
Basic idea of select sorting: from arr[0] for the first time~
Select the minimum value in arr[n-1] and exchange with arr[0]; Second from arr[1]~
Select the minimum value in arr[n-1] and exchange with arr[1]; Select the minimum value from arr[2]~arr[n-1] for the third time, exchange with arr[2],,, and from arr[i] ~ arr[n-1], The n-1st time from arr[n-1]~
The minimum value of arr[n-1] is selected and exchanged with arr[n-2]. A total of n-1 times is passed to obtain an ordered sequence from small to large
Algorithm steps
First, find the smallest (large) element in the unordered sequence and store it at the beginning of the sorted sequence.
Then continue to find the smallest (large) element from the remaining unordered elements, and then put it at the end of the sorted sequence.
Repeat step 2 until all elements are sorted.
Code implementation:
public static void main(String[] args) { //Create an array with a size of 8 and assign an initial value to it int[] arr = {1,8,2,5,7,4,3,9}; int length = arr.length; for(int i = 0 ;i < length-1;i++) { //Set the subscript of the minimum value to i before each lookup int minFlag = i; for(int j = i+1;j < length;j++) { if(arr[j] < arr[minFlag]) { //Record the subscript of the minimum value for each cycle minFlag = j; } } //At the end of a large cycle, the first data of this round is exchanged with the smallest data position int temp = arr[i]; arr[i] = arr[minFlag]; arr[minFlag] = temp; } }
Insert sort
Insert sort
Basic idea of Sorting: the n elements to be sorted are regarded as an ordered and an unordered table. At the beginning, the ordered table contains only one element, and the unordered table contains n-1 elements. In the process of Sorting, the first element is taken out from the unordered flag every time, its Sorting code is compared with the Sorting code of the elements of the ordered table in turn, and it is inserted into the appropriate position in the ordered table, Make it a new ordered table
Algorithm steps
The first element of the first sequence to be sorted is regarded as an ordered sequence, and the second element to the last element is regarded as an unordered sequence.
Scan the unordered sequence from beginning to end, and insert each scanned element into the appropriate position of the ordered sequence. (if the element to be inserted is equal to an element in the ordered sequence, the element to be inserted is inserted after the equal element.)
Code implementation:
public static void main(String[] args) { //Create an array with a size of 8 and assign an initial value to it int[] arr = {1,8,2,5,7,4,3,9}; int length = arr.length; for(int i = 1;i < length;i++) { //Record the data to be compared at present int temp = arr[i]; //Record the location of the current data int j = i; //If the subscript is greater than zero and the previous element of this subscript is greater than the element to be replaced, move the elements back, because the previous elements are all arranged, so you don't need to consider the previous order while(j > 0 && temp > arr[j-1]) { arr[j] = arr[j-1]; j--; } //If the final location is found if(j != i) { arr[j] = temp; } } }
Shell Sort
Hill sort is also an insert sort. It is a more efficient version of simple sort after improvement, also known as reduced incremental sort.
Hill sort (Donald)
Shell) basic idea: Hill sorting is to group records according to a certain increment of subscript, and use direct insertion sorting algorithm for each group; As the increment decreases, each group contains more and more keywords,. When the increment is reduced to 1, the whole file is just divided into a group, and the algorithm is terminated
Algorithm steps:
Select an incremental sequence t1, t2,..., tk, where ti > TJ, tk = 1;
Sort the sequence k times according to the number of incremental sequences k;
For each sorting, the sequence to be sorted is divided into several subsequences with length m according to the corresponding increment ti, and each sub table is directly inserted and sorted. Only when the increment factor is 1, the whole sequence is treated as a table, and the table length is the length of the whole sequence.
Code implementation:
//[exchange type] public static void main(String[] args) { //Create an array with a size of 8 and assign an initial value to it int[] arr = {1,8,2,5,7,4,3,9}; int length = arr.length; //gap is the number of groups. The first group is the array, and the total number of elements is 2. Then continue to divide the current number of groups by 2 until the number of groups is 1 for(int gap = length/2;gap > 0;gap /= 2) { //The cyclic comparison starts from the first of each group for(int i = gap;i < length;i++) { //Find the first few leading elements of each group in turn, and compare and insert them for(int j = i - gap;j >= 0;j -= gap) { if(arr[j] > arr[j+gap]) { int temp = arr[j]; arr[j] = arr[j+gap]; arr[j+gap] = temp; } } } } }
//[shift type] public static void main(String[] args) { //Create an array with a size of 8 and assign an initial value to it int[] arr = {1,8,2,5,7,4,3,9}; int length = arr.length; //Each group is arranged in order until the number of groups is 1 for(int gap = length/2; gap > 0;gap/=2) { //Insert and sort different groups for(int i = gap;i < length;i++) { int temp = arr[i]; int j = i; while(j-gap >= 0 && temp < arr[j-gap]) { arr[j] = arr[j-gap]; j -= gap; } if(j != i) { arr[j] = temp; } } }
Quick sort
QuickSort is an improvement of bubble sort. The basic idea is to divide the data to be sorted into two independent parts through one-time sorting. All the data in one part is smaller than all the data in the other part, and then quickly sort the two parts of data respectively according to this method. The whole sorting process can be recursive
Algorithm steps:
1. Pick out an element from the sequence, which is called "pivot";
2. Reorder the sequence. All elements smaller than the benchmark value are placed in front of the benchmark, and all elements larger than the benchmark value are placed behind the benchmark (the same number can be on either side). After the partition exits, the benchmark is in the middle of the sequence. This is called a partition operation;
3. Recursively sort the subsequence less than the reference value element and the subsequence greater than the reference value element;
[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-3urmei31-1636711015598)( https://img-bog.csdnimg.cn/cba219d644ee4a808c0945c31f7d7a3e.gif#pic_center )]
Code implementation:
public static void quickSort(int[] arr , int left ,int right) { int r = right;//Left subscript int l = left;//Right subscript //Central axis value int pivot = arr[(r + l)/2]; //Put numbers smaller than pivot on the left and numbers larger than pivot on the right in the array while(l < r) { //Start at the far left while(arr[l] < pivot) { l++; } //Start at the far right while(arr[r] > pivot) { r--; } //If you don't find it, quit if(l >= r) { break; } //If you don't quit, it means you have found it and exchange data int temp = arr[l]; arr[l] = arr[r]; arr[r] = temp; //After the exchange, if it is found that arr[l] == pivot, move r forward one step if(arr[l] == pivot) { r--; } //After the exchange, if it is found that arr[r] == pivot, let l move back one step if(arr[r] == pivot) { l++; } //If l == r, let l++,r -- otherwise stack overflow will occur if(l == r) { l++; r--; } //Left recursion if(left < r) { quickSort(arr,left,r); } //Recursive right if(right > l) { quickSort(arr,l,right); } }
Merge sort
Merge sort is a sort method based on the idea of merging. The algorithm adopts the classical divide and conquer strategy (divide and conquer divides the problem into some small problems and then solves them recursively, and the stage of governance combines the answers obtained in different stages, that is, divide and conquer)
Algorithm steps:
1. Apply for space so that its size is the sum of two sorted sequences, and the space is used to store the merged sequences;
2. Set two pointers. The initial positions are the starting positions of the two sorted sequences respectively;
3. Compare the elements pointed to by the two pointers, select the relatively small elements into the merge space, and move the pointer to the next position;
4. Repeat step 3 until a pointer reaches the end of the sequence;
5. Copy all the remaining elements of another sequence directly to the end of the merged sequence.
Code implementation:
public static void Mergesort(int[] arr,int left,int right,int[] temp) { if(left < right) { int mid = (left + right) / 2; //Split the left array Mergesort(arr, left, mid, temp); //Split right array Mergesort(arr,mid+1,right,temp); //merge Merge(arr,left,mid,right,temp); } } public static void Merge(int[] arr,int left,int mid,int right,int[] temp) { int l = left; int j = mid + 1; int t = 0; while(l <= mid && j <= right) { //If the elements in the left ordered sequence are smaller than those in the right ordered sequence, copy the elements on the left to the temp array. On the contrary, copy the elements on the right if(arr[l] < arr[j]) { temp[t++] = arr[l++]; }else { temp[t++] = arr[j++]; } } //If the left element is not copied, copy the remaining elements while(l <= mid) { temp[t++] = arr[l++]; } //If the elements on the right are not copied, copy all the remaining elements on the right while(j <= right) { temp[t++] = arr[j++]; } //Copy the elements of the temp array to the arr array t = 0; int tempLeft = left; while(tempLeft <= right) { arr[tempLeft++] = temp[t++]; } }
Cardinality sort
Basic idea of Radix sorting: unify all values to be compared into the same digit length, fill zero in front of the number with shorter digits, and then sort in turn from the lowest bit to the highest bit. After sorting, the sequence becomes an ordered sequence
Cardinality sorting Description:
(1) Cardinality sorting is an extension of the traditional bucket sorting, which is very fast
(2) Cardinality sorting is a classic space for time method, which takes up a lot of memory space. When sorting massive data, it is easy to cause OutOfMemoryError.
(3) Cardinality sorting is stable. [Note: assuming that there are multiple records with the same keyword in the record sequence to be sorted, if the gold is sorted, the relative order of these records remains unchanged, that is, in the original sequence, r[i] =r[j], and r[i] is before r[j], but in the sorted sequence, r[i] is still before r[j], then this sorting algorithm is called stable, otherwise it is called unstable]
(4) When there are negative numbers, try not to use cardinality sorting. If you want to use cardinality sorting, you should improve it
Code implementation:
public static void main(String[] args) { //Create an array with a size of 8 and assign an initial value to it int[] arr = {190,82,25,512,754,4,143,9}; radixSort(arr); System.out.println(Arrays.toString(arr)); } public static void radixSort(int[] arr) { //Find the maximum number of digits in the array to be arranged int max = arr[0]; for(int i = 1;i < arr.length;i++) { if(arr[i] > max) { max = arr[i]; } } //Number of digits to determine the maximum number of digits int len = (max+"").length(); //What are the data records put into each same int[][] bucket = new int[10][arr.length]; //Record the number of data put into each bucket int[] buckNumber = new int[10]; //Bucket sorting by different digits for(int i = 0,n = 1;i < len;i++,n *= 10) { //Loop through the data in the array and put it into the bucket for (int j = 0; j < arr.length; j++) { //Take out the data on each digit int temp = arr[j] / n % 10; bucket[temp][buckNumber[temp]] = arr[j]; //When there is one more data in the specified bucket, add one to the total number of data in this bucket buckNumber[temp]++; } //Take out the data in the bucket in the order of the bucket int temp = 0; for (int k = 0; k < buckNumber.length; k++) { if (buckNumber[k] != 0) { for (int j = 0; j < buckNumber[k]; j++) { arr[temp++] = bucket[k][j]; } } //At the end of each cycle, you need to clear the array storing the number of elements in each same cell buckNumber[k] = 0; } } }