public class QuickSortDemo {
public static void main(String[] args) {
int[] array = {9, 6, 7, 6, 5, 4, 3, 2, 6, 0};
printArray(array);
quickSort(array);
printArray(array);
}
private static void quickSort(int[] array) {
if (Objects.isNull(array) || array.length == 1) {
return;
}
arrayPartQuickSort(array, 0, array.length - 1, 0);
}
private static void arrayPartQuickSort(int[] array, int startIndex, int endIndex, int baseIndex) {
if (endIndex - startIndex < 1) {
return;
}
int tempStartIndex = startIndex;
int tempEndIndex = endIndex;
int tempBaseValue = array[baseIndex];
int tempStartValue;
int tempEndValue;
while (true) {
while(true) {
tempEndValue = array[tempEndIndex];
if (tempEndValue < tempBaseValue) {
break;
}
if (tempEndIndex > tempStartIndex) {
tempEndIndex --;
} else {
break;
}
}
while(true) {
tempStartValue = array[tempStartIndex];
if (tempStartValue > tempBaseValue) {
break;
}
if (tempStartIndex < tempEndIndex) {
tempStartIndex ++;
} else {
break;
}
}
if (tempStartIndex == tempEndIndex) {
break;
}
int swapValueTemp = array[tempEndIndex];
array[tempEndIndex] = array[tempStartIndex];
array[tempStartIndex] = swapValueTemp;
}
int swapValueTemp = array[baseIndex];
array[baseIndex] = array[tempEndIndex];
array[tempEndIndex] = swapValueTemp;
arrayPartQuickSort(array, startIndex, tempEndIndex - 1, startIndex);
arrayPartQuickSort(array, tempEndIndex + 1, endIndex, tempEndIndex + 1);
}
private static void printArray(int[] array) {
if (Objects.isNull(array)) {
System.out.println(array);
}
for (int item : array) {
System.out.print(item + " ");
}
System.out.println();
}
}
快速排序
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 选择排序 对于任何输入,时间为O(n*n); 冒泡排序 最优(对于升序的数组,因为加入了一个跳出判断):O(n),...
- 欢迎探讨,如有错误敬请指正 如需转载,请注明出处http://www.cnblogs.com/nullzx/ 1....
- 给定数组 int[] arr = {3,6,8,4,7,5,9,1,2,0};使用至少三种方法对数组arr排序(作...
- 用Objective-C实现几种基本的排序算法,并把排序的过程图形化显示。其实算法还是挺有趣的 ^ ^. 选择排序...