Divided:
Specify a critical value key
From the left and right side of the Loop division operation, will be less than equal to the left side of key, greater than or equal to the key of the put
The divided sequence is not necessarily all ordered.
O (N) Only one trip to sort
/** * divided * * @author stone * @date 2015-7-29 pm 4:37:16 */public class Partition {public static void main (string[] args ) {int[] ary = Util.generateintarray (10); Util.printarray (ary); int pivot = 3;int Partdex = sort (ary, 0, ary.length-1, pivot); SYSTEM.OUT.PRINTLN ("Key value is" + Pivot + ", the dividing Index is" + Partdex "); Util.printarray (ary);} private static int sort (int[] ary, int left, int. right, int pivot) {int leftptr = left-1; Left again left one operation need first ++int rightptr = right + 1; --while (True) {while (Leftptr < R && Ary[++leftptr] <= pivot) is required for right-side operation, and//leftptr points to items > key values Stop while (Rightptr > left && ary[--rightptr] >= pivot); Rightptr points to the item < key value Stop if (leftptr >= rightptr) {break;} else {//leftptr rightptr points to an item that is not in the correct location should swap swap (ary, leftp TR, rightptr);} /* Continue to the next cycle. The item in the previous error location has been swapped. The left and right hand pointer continues to move */}system.out.println ("l=" + leftptr + ", r=" + rightptr); return rightptr;//returns leftptr also}private static void swap (int[] ary, int a, int b) {int temp = Ary[a];ary[a] = ary[b];ary[b] = temp;}}
Output
[2, 6, 9, 8, 4, 0, 5, 1, 7, 3]l=3,r=2 the key value is 3, the index is 2[2, 1, 0, 8, 4, 9, 5, 6, 7, 3]
Results:
Location in <=index <key; In >index's position >=key
Or
Location in <=index <=key; In >=index's position >key
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Division Sort