Quick Sort Java Version

Source: Internet
Author: User

Import Java.util.Random;

Public class Test {
public static void Main (string[] args)
{
int[] arr=generatenumbers;
Show (arr, " Before sort: ");
Quicksort (arr,0,arr.length-1);
Show (arr, "after sort:");
}

static void Quicksort (int[] arr,int l, int r)
{
if (l>=r) return;
int I=l;int j=r;
int Pivot=arr[i];//pivot
while (i<j)
{
//from-left find the number less than pivot
while (i <j && arr[j]>=pivot) j--;
if (i<j) arr[i++]=arr[j];
//Now the empty position are Arra[j]
//from left to right find the number bigger than pivot
while (i<j &&A mp Arr[i]<=pivot) i++;
if (i<j) arr[j--]=arr[i];
}
//when i==j then the empty position are i/j so we should set the pivot
Arr[i]=pivot;
Recursive call the method
Quicksort (arr,l,i-1);
Quicksort (ARR,I+1,R);

}

Static int[] Generatenumbers (int length)
{
Random r = new Random ();
int [] arr = new Int[length];
for (int i=0;i<length;i++)
Arr[i]=r.nextint (100);
return arr;
}

static void Show (int[] arr,string msg)
{
SYSTEM.OUT.PRINTLN (msg);
for (int i=0;i<arr.length;i++)
System.out.print (Arr[i] + "\ t");
System.out.println ();
}

Quick Sort Java Version

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.