Quick Sorting Algorithm and Sorting Algorithm
Like the merge sort algorithm, the quick sort algorithm uses the grouping principle to sort unordered arrays until they finally form an ordered array. The principle of the quick sorting algorithm is to extract a number (usually the first or last element) from an unsorted array as the principal element, put the elements smaller than the primary element in the unordered array to the left of the primary element, and those greater than the primary element to the right of the primary element. Then, all the elements on the left of the principal component are processed according to the above method, and the elements on the right are the same, and so on. The sorting is completed until only one element is left in the array on both sides of the left and right. Next we will use a picture to demonstrate the fast Sorting Algorithm:
From the figure above, we can see that the array sorting is complete when the Division is complete.
The following is the java code of the Quick Sort Algorithm:
The program is divided into two methods. The method QuickSort is used to determine whether to continue partitioning. The method Partition is used to select the principal component and divide unordered arrays.
Public static void QuickSotrt (int [] array, int head, int tail) {if (head <tail) {// obtain the principal position int k = Partition (array, head, tail); // re-divide the elements on the left of the principal component QuickSotrt (array, head, k-1); // re-divide the array on the right of the principal component QuickSotrt (array, k + 1, tail) ;}} public static int Partition (int [] array, int head, int tail) {// select the first one as the principal component to divide int j = head; int temp; // compare the number in the loop array with the first data in the array and divide it for (int I = head + 1; I <= tail; I ++) {if (array [I] <array [head]) {temp = array [I]; array [I] = array [++ j]; array [j] = temp ;}/// place the principal component in the middle of the left and right arrays. temp = array [head]; array [head] = array [j]; array [j] = temp; return j ;}
The time complexity of the quick sorting algorithm is O (n ^ 2). In the fast Sorting Algorithm with randomly selected principal components, the expected time complexity can reach O (nlogn ), the space complexity is O (1 ).