/** * Quick Sort Implementation * Created by John Kwok on 2018/2/2. */import Java.util.arrays;public class QuickSort {/** * Randomly selects a numeric value within the range to be sorted, places a number less than or equal to the value at that index on its left side, and is greater than the right side of the index. * @param array * @param start * @param end * @return */public static int partition (int[] Array,int STA Rt,int end) {if (array = = null| | Array.Length = = 0| | start<0 | | End >= Array.Length | | Start>end) return-1; if (start = = end) return start; int index = (int) (Start + math.random () * (End-start + 1)); Swap (array,index,end); int smallnum = start-1;//note here for (int i = start; I <= end; i++) {if (Array[i] <= Array[end]) { smallnum++; if (i > Smallnum) {swap (array,i,smallnum); }}} return smallnum; }/** * Use recursion to quickly sort * @param array * @param start * @param end */public static void Quicksortfu N (int[] array,int Start,int end) { if (array = = null| | Array.Length = = 0| | Start <0| | End >=array.length| | Start > End) return; int index = partition (Array,start,end); if (Index > Start) quicksortfun (array,start,index-1); if (Index < end) Quicksortfun (array,index+1,end); }/** * Swap values at two indices in the array * @param array * @param i * @param j */public static void Swap (int[] Array , int i,int j) {int temp = Array[i]; Array[i] = Array[j]; ARRAY[J] = temp; }/** * Main function, validation method * @param args */public static void main (string[] args) {int[] array = new int[] {1,2,7,3,5,4,2,7,9,2,2,5,76,2,5,2,6,3};//int[] array = new int[]{1,2};//swap (array,0,1); Quicksortfun (array,0,array.length-1); System.out.println ("Sort result:" +arrays.tostring (array)); }}
Quick Sort