change pivot in my quickSort algorithm java(在我的快速排序算法java中更改枢轴)
问题描述
I have implemented a working quickSort algorithm using the first element in the array as the pivot, that look like this:
public int[] quickSort( int[] a, int start, int end){
int l = start;
int r = end;
int pivotIndex = start; //<---- first element in the array as pivot!
// must be at least two elements
if ( end - start >= 1){
// set pivot
int pivot = a[pivotIndex];
while ( r > l ){
// scan from the left
while ( a[l] <= pivot && l <= end && r > l ){
l++;
}
while ( a[r] > pivot && r >= start && r >= l){
r--;
}
if ( r > l ){
this.swap(a, l, r);
}
}
this.swap(a, pivotIndex, r);
System.out.println("calling quickSort on " + start + " and " + (r-1));
quickSort(a, pivotIndex, r - 1); // quicksort the left partition
System.out.println("calling quickSort on " + (r+1) + " and " + end);
quickSort(a, r + 1, end); // quicksort the right partition
} else {
return a;
}
return a;
}
And this works nicely, but if I change the pivotIndex
to lets say int pivotIndex = end;
I get this result:
run:
2, 8, 7, 1, 3, 5, 6, 4,
2, 8, 7, 1, 3, 5, 6, 4,
swapping l:8 and r:4
2, 4, 7, 1, 3, 5, 6, 8,
swapping l:7 and r:3
2, 4, 3, 1, 7, 5, 6, 8,
swapping l:8 and r:1
calling quickSort on 0 and 2
calling quickSort on 4 and 7
2, 4, 3, 8, 7, 5, 6, 1,
swapping l:7 and r:1
2, 4, 3, 8, 1, 5, 6, 7,
swapping l:7 and r:1
calling quickSort on 4 and 3
calling quickSort on 5 and 7
2, 4, 3, 8, 7, 5, 6, 1,
swapping l:5 and r:1
2, 4, 3, 8, 7, 1, 6, 5,
swapping l:5 and r:1
calling quickSort on 5 and 4
calling quickSort on 6 and 7
2, 4, 3, 8, 7, 5, 6, 1,
swapping l:6 and r:1
2, 4, 3, 8, 7, 5, 1, 6,
swapping l:6 and r:1
calling quickSort on 6 and 5
calling quickSort on 7 and 7
2, 4, 3, 8, 7, 5, 6, 1,
BUILD SUCCESSFUL (total time: 1 second)
How to I make the algorithm work with the pivotIndex as any index 0 to a.length
You could simply swap the pivot you chose with the first element in the array before you start sorting, that way it'll work exactly as before.
int l = start;
int r = end;
this.swap(a, choosePivot(), start);
int pivotIndex = start;
这篇关于在我的快速排序算法java中更改枢轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在我的快速排序算法java中更改枢轴
基础教程推荐
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01