Let's start with the simple. (results from small to large), where quick sorting and selection sorting are not stable.
1. Select sort
The advantage of choosing a sort is that the number of exchanges is less, the worst case time complexity is O (N2), and the best case is O (N2)
Public Static voidSortint[] num) { for(inti = 0;i < num.length;i++){ intK = 0; for(intj = i + 1;j < num.length;j++){ if(Num[k] >Num[j]) { inttemp =K; K=J; J=temp; } } if(k! =i) { inttemp =Num[k]; NUM[K]=Num[i]; Num[i]=temp; } } }
2. Bubble sort
Bubble sort in the worst case algorithmic complexity is O (N2), Best case O (n)
Public Static voidSortint[] nums) { for(inti = 0; i < nums.length-1; i++) { intSwap = 0; for(intj = 0; J < nums.length-1-I; J + +) { if(Nums[j] > nums[j + 1]) { inttemp =Nums[j]; NUMS[J]= Nums[j + 1]; Nums[j+ 1] =temp; Swap= 1; } } if(Swap = = 0) { Break; } } }
3. Insert Sort
The insertion sort is faster in basic order, the worst-case time complexity is O (N2), and the best case is O (n)
Public Static void sort (int[] nums) { int length = nums.length; for (int i = 1; i < length; i++) { for (int j = i; j > 0 && num S[J] < nums[j-1]; j--) { int temp = nums[j]; = Nums[j-1]; -1] = temp;}} }
4. Merge sort
Merge sort is slightly more difficult, time complexity is O (NLOGN)
Public Static voidSortint[] Nums,intLowintHigh ) { intMID = low + (high-low)/2; if(Low <High ) {Sort (nums, low, mid); Sort (Nums, mid+ 1, high); Merge (Nums, Low, Mid, high); } } Public Static voidMergeint[] Nums,intLowintMidintHigh ) { int[] temps =New int[High-Low + 1]; inti =Low ; intj = Mid + 1; intK = 0; while(I <= mid && J <=High ) { if(Nums[i] <Nums[j]) {Temps[k+ +] = nums[i++]; } Else{temps[k+ +] = nums[j++]; } } while(I <=mid) {temps[k+ +] = nums[i++]; } while(J <=High ) {Temps[k+ +] = nums[j++]; } for(intK2 = 0; K2 < Temps.length; k2++) {Nums[low+ K2] =TEMPS[K2]; } }
5. Quick Sort
The time complexity for quick sorting is O (NLOGN)
Public Static voidSortint[] Nums,intLowintHigh ) { if(Low <High ) { intPosition =partition (Nums, Low, high); Sort (nums, low, position); Sort (nums, Position+ 1, high); } } Public Static intPartitionint[] Nums,intLowintHigh ) { inti = low, j =High ; intx =Nums[low]; while(I <j) { while(I < J && Nums[j] >=x) {J--; } if(I <j) {Nums[i]=Nums[j]; I++; } while(I < J && Nums[i] <x) {i++; } if(I <j) {Nums[j]=Nums[i]; J--; }} Nums[i]=x; returni; }
Select, bubble, insert, merge, quick sort (Java implementation)