Java Division Sort

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.