The fast sorting algorithm, like the merge sort algorithm, is based on the principle of divide and conquer by continually sorting an unordered array until the final formation of an ordered array. The principle of the fast sorting algorithm is to take a number (usually the first or last element) as the principal element in an array that is not sorted, placing the elements of the unordered array smaller than the main element on the left side of the main element, and the elements greater than the main element on the right side of the main element. Then all elements on the left side of the main element that are smaller than the main element are treated as above, and the elements on the right are the same, and so on. The sorting is done until the last left and right arrays are left with only one element. Next we use a graph to illustrate the next fast sorting algorithm:
As you can see from the diagram above, when the partitioning is complete, the array sort is complete.
The following is the Java code for the Quick sort algorithm:
The program is divided into two methods, the method quicksort to determine whether to continue the division, the method partition to select the main element, the unsorted array is divided.
Public Static voidQUICKSOTRT (int[] Array,intHeadinttail) { if(Head <tail) { //get the main element location intK =Partition (array, head, tail); //re-dividing the left element of the main elementQUICKSOTRT (Array, head, k-1); //re-dividing the right array of the main elementQUICKSOTRT (Array, k+1, tail); } } Public Static intPartition (int[] Array,intHeadinttail) { //Select the first to be divided as a main element intj =Head; inttemp; //number in the loop array, compared to the first data in the array for(inti=head+1;i<=tail;i++){ if(Array[i] <Array[head]) {Temp=Array[i]; Array[i]= array[++J]; ARRAY[J]=temp; } } //Places the main element in the middle of the left and right arraytemp =Array[head]; Array[head]=Array[j]; ARRAY[J]=temp; returnJ; }
The time complexity of the fast sorting algorithm is O (n^2), and the expected time complexity can reach O (NLOGN) and the space complexity is O (1) in the fast sorting algorithm of randomly selected main elements.
Fast sorting algorithm