Insert sort: Starting with 1, the i is inserted into the ordered sequence of its left end by swapping. The number of exchanges is uncertain, but the number of comparisons is more balanced. Better than bubbling.
1 Private Static void Charu (intintint len) {2for (int i = off; I < Len + off; i++)3for (int j = i; j > off && x[j-1] > x[j]; j--) 4 swaps (x, J, J-1); 5 }
Select sort: Similar to bubbling, each trip finds the index of the smallest number from I to the end, then exchanges with I for a trip with only one exchange, so faster than bubbling.
1 Private Static voidXuanze (intX[],intOffintLen) {2 for(inti = off; I < Len + off; i++) {3 intMin =i;4 for(intj = min; J < Len + off; J + +) {5 if(X[min] >X[j])6Min =J;7 }8 Swap (x, I, min);9 }Ten}
Bubble sort: I from left to right, I fixed will be from I to the end of the minimum number to move to I, complete a trip, and so on until I to the right end through non-stop exchange completed, time consumption more.
1 Private Static voidMaopao (intX[],intOffintLen) {2 for(inti = off; I < Len + off-1; i++) {3 for(intj = i; J < Len + off; J + +) {4 if(X[i] >X[j])5 Swap (x, I, j);6 }7 }8}
Quick Sort method: First select any data as the key data, and then put all the smaller than its number in front of it, all the larger than its number is placed behind it, this process is called a fast sort of a trip. Then recursion.
Algorithm: 1) I from left to right to find larger than key, I moved here; J from right to left to find smaller than key, J move Here
2) If the i<j is exchanged for IJ, repeat 1); otherwise, a trip is completed.
3) After the completion of a trip I if not to the right end, recursion to the right; if the left end is not reached, the recursive left side of the algorithm can be improved, please refer to the JDK source code.
1 Private Static voidKuaisu (intX[],intOffintLen) {2 intm = off + (len >> 1);//mid-position subscript3 intleft = off;//Start subscript4 intright = off + len-1;//End Subscript5m =med3 (x, left, M, right);6 intkey = X[m];//take the middle one as the key data7 //System.out.println ("key=" +key);8 inti =Left ;9 intj =Right ;Ten while(true) { One while((X[i] < key) && (I <Right )) A //from left to right, looking for >=. -i++; - while((X[j] > key) && (J >Left )) the //looking for <= from right to left. -j--; - if(I >=j) { - Break;//a trip to complete + } - Swap (x, I, j); +System.out.printf ("Swap%d%d:%s\n", I, J, arrays.tostring (x)); A } at if(I <Right ) -Kuaisu (x, i + 1, right-i); - if(J >Left ) -Kuaisu (x, left, J-Left ); -}
To find a value in the middle of the subscript:
1 Private Static int med3 (int. int int int c) {2 return (X[a] < x[b]? (X[b] < X[c]? B:x[a] < X[c]? c:a) 3 : (X[b] > X[c]? b:x[a] > X[c]? c:a)); 4 }
Swap a B position in array x:
1 Private Static void swap (intintint b) {2 int t = x[a]; 3 X[a] = x[b]; 4 X[B] = t; 5 }
Several sort algorithms in Java