1. Fast sorting is a split algorithm that divides an array into two arrays and sorts them independently by two arrays.
2. Quick sort and Merge sort are complementary: merge sort occurs before the recursive call occurs before the array is processed, the quick sort takes place after the recursive call sort, in the merge sort, an array is divided into two halves, in the quick sort, the slice (partition) position depends on the concrete contents of the array.
:
Algorithm implementation:
1 Public classQuick2 {3 Public Static voidsort (comparable[] a)4 {5Stdreadom.shuffle (a);//eliminate dependency on the original array6Sort (a,0,a.length-1);7 }8 Private Static voidSort (Comparable[]a,intLointhi)9 {Ten if(hi<=lo) One return; A intJ=partion (A,lo,hi);//Segmentation function -Sort (a,lo,j-1), the left half from Lo to Jsort of 1 - Sort (A,j,hi); the left half is sorted from J to Hi the } -}
Quick-Sort Segmentation
1 Private Static voidPartion (Comparable[]a,intLointhi)2 {3 //cut the array into A[lo,..., i-1],a[i],a[i+1,..., Hi]4 inti=lo,j=hi+1;//Scan left and right hands5Comparable V=a[lo];//slicing elements6 while(true)7 {8 //scan left and right elements, check if scan is over and swap elements9 while(Less (A[++I],V))if(i==hi) bresk;Ten while(Less (v,a[--j]))if(j==lo) Bresk; One //the less (a, B) function implements the If a<b, returns ture, otherwise false; A if(I>=J) Break; -Exch (A,i,j);//This function implements the interchange A[i],a[j] - } theExch (A,lo,j);//Place the shard element in the correct position - returnJ//the slice element will be left and right -}
Here is the Shard display (array contents before and after each interchange):Note: 1. In-situ division: If you use an auxiliary array, we can easily implement the partition, but the partition after the array to copy back to the original array, this part of the cost is we lose the candle, greatly reduce the sorting speed of 2. Do not cross the border: if the Shard element is the largest or smallest element in the array, Caution The pointer throws an array boundary 3. Keep randomness: Array elements begin to eliminate input dependencies on arrays, and treat all sub-arrays equally 4. Terminating recursion: A common mistake in fast ordering is that the segmentation element is not guaranteed to be placed in the correct position, causing the program to be the largest or smallest of the sub-arrays. Into the infinite loop.
Classic algorithms-Quick sort