public void random_partion(int start, int length) {//核心代码(随机位置二分排序)
if (length <= 1)
return;
Random rand = new Random();
int index = rand.nextInt(length) + start;
int i = start - 1;
int j = start;
// System.out.println("start--->"+start+"length--->"+length+"i--->"+i+"j--->"+j+"index--->"+index+"start+length-1--->"+(start+length-1));
this.swap(index, start + length - 1);
for (j = start; j < start + length; j++) {
if (initArray[j] < initArray[start + length - 1]) {
this.swap(++i, j);
}
}
this.swap(++i, start + length - 1);
random_partion(start, i - start + 1);
random_partion(i + 1, length + start - i - 1);
}
public int[] quickSorted() {
this.random_partion(0, initArray.length);
return initArray;
}
public void swap(int a, int b) {
int temp = initArray[a];
initArray[a] = initArray[b];
initArray[b] = temp;
}
java实现快速排序(利用随机索引)
最新推荐文章于 2022-09-15 22:38:21 发布