package algorithms;
import java.util.Random;
public class QuickSort {
private static Random rand = new Random();
/**
* 快速排序法
*/
public static void main(String[] args) {
int[] b = new int[rand.nextInt(100)];
for(int i = 0; i < b.length; i++)
b[i] = rand.nextInt(100);
quickSort(b, 0, b.length - 1);
for(int i : b){
System.out.print(i + " ");
}
}
private static void quickSort(int[]a, int p, int r){
while(p < r){
int q = randomPartition(a, p, r);
quickSort(a,p,q-1);
p++;
}
}
private static int partition(int[] a, int p, int r){
int x = a[p];
int i = p -1;
for(int j = p; j <= r; j++){
if(a[j] <= x){
i++;
swap(a,i,j);
}
}
swap(a,p,i);
return i;
}
private static int randomPartition(int[] a, int p, int r){
int i = rand.nextInt(r - p) + p;
swap(a,p,i);
return partition(a, p, r);
}
private static void swap(int[] a, int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
快速排序Java代码
最新推荐文章于 2024-09-29 09:19:41 发布