天天看点

quick sort java version

import java.util.Random;

public class test {

public static void main(String[] args)

{

int[] arr= generatenumbers(10);

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 right to 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 is arra[j]

//from left to right find the number bigger than pivot

while(i<j && arr[i]<=pivot) i++;

if(i<j)arr[j--]=arr[i];

}

//when i==j then the empty position is 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] + " ");

System.out.println();

}