关于常规解法,请参考上一篇博客,链接如下:
介绍一种优雅的解法
public int partition(int data[],int length,int start,int end) throws Exception{
if(data == null || length <= 0||start < 0||end >= length){
throw new Exception("invalid data");
}
//RandomInrange是一个随机函数,随机选取start和end中间的随机值
int index = RandomInrange(start,end);
//swap是一个交换函数
swap(data[index],data[end]);
int small = start -1;
for(index = start; index < end;index++){
if(data[index] < data[end]){
++small;
if(small != index){
data[small] = data[index];
}
}
}
small++;
swap(data[small],data[end]);
return small;
}
static void quicksort(int n[], int length,int left, int right) {
//对特殊值和边界值的检查,提高程序的鲁棒性
if(n == null || left < 0){
return;}
int dp;
if (left < right) {
dp = partition(n, length,left, right);
quicksort(n, length,left, dp - 1);
quicksort(n, length,dp + 1, right);
}
}
时间: 2024-11-02 13:30:47