Fast sorting is a sort algorithm of divide and conquer. It divides an array into two sub-arrays, sorting the two parts independently. The quick sort and merge sort are complementary, the merge sort sorts the two sub-arrays and merges the ordered sub-arrays to sort the entire array, while the fast sort is the whole array is naturally ordered when the two sub-arrays are ordered. In a quick sort, the location of the slice depends on the contents of the array.
Advantages:
1. Simple to implement;
2. Suitable for a variety of different input data and in general applications than other sorting algorithms are much faster;
3. Sort in situ;
4. Time complexity is O (NLGN);
5. The inner loop is shorter than most sorting algorithms and less frequently compared.
Cons: The fast sorting algorithm is very fragile and is implemented with great care to avoid poor performance.
The code is as follows:
/** * * @author seabear * */public class QuickSort {public static Boolean less (comparable v,comparable W) {return V.compar ETo (W) < 0;} public static void Exch (comparable[] A,int I,int j) {Comparable temp = a[i];a[i] = a[j];a[j] = temp;} public static void sort (comparable[] a) {sort (A, 0, a.length-1);} public static void Sort (comparable[] a,int lo,int hi) {if (Hi <= lo) {return;} Int J = partition (A,lo,hi); sort (A, lo, j-1); sort (A, j + 1, HI);} public static int partition (comparable[] a,int lo,int hi) {int i = lo; Comparable v = a[lo];int j = Hi + 1;while (true) {while (less (a[++i],v)) {if (i = = hi) {break;}} while (less (v,a[--j)) {if (j = = lo) {break;}} if (i >= j) {break;} Exch (a,i,j);} Exch (A, Lo, j); return J;} public static void Show (comparable[] a) {for (int i = 0; i < a.length; i++) {System.out.print (A[i] + "");} System.out.println ();} public static void Main (string[] args) {integer[] a = new Integer[10];for (int i = 0; i <; i++) {a[i] = (int) (Math.rand Om () * 10 + 1);} Show (a); Sort (A); show (A);}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Algorithm (fourth edition) Learning Notes Java implementation Quick Sort