快速排序算法实现方式2,来自Algorithm4 这本书的例子。这种方式有点不好理解(根使用comprable数组,而没用使用不同的int[]数组没有关系)。
这种方式的逻辑就是不断从低位找比第一个元素(这里拿第一个元素做基准元素)大的元素,同时从高位开始找比第一个元素小的元素,找到后,将这两个元素交换。直到低位的指针大于等于高位的指针。这是将第一个元素与高位指针对应的元素交换。将左右两个子数组再进行快速排序。
这里有分治和回溯的思想。
package indi.tom.Algorithm.recursion.sort;
import java.util.Arrays;
/**
* @Author Tom
* @Date 2019/11/11 9:44
* @Version 1.0
* @Description The Quick Sort
*/
public class QuickSort {
//This is an util class, so should not be instantiated
private QuickSort(){}
public static void main(String[] args) {
String[] array = {"i","q","w","e","r","t","y","u","i","o","p","a","s",
"d","f","g","h","j","k","l","z","x","c","v","b","n","m"};
quickSort(array, 0, array.length - 1);
for (int i = 0; i < array.length; i++) {
System.out.printf("%s ",array[i]);
}
}
public static void quickSort(Comparable[] array, int low, int high){
if (high <= low) return;
int j = partition(array, low, high);
quickSort(array,low, j-1);
quickSort(array,j+1,high);
}
public static int partition(Comparable[] array, int low, int high){
//need to validate the input?
int i = low;
int j = high + 1;
Comparable temp = array[low];
while(true){
//iterate the array from left, if the element is greater than temp, then exit the loop
while(array[++i].compareTo(temp) < 0){
if(i == high) break;
}
//no consideration when equal?
while(array[--j].compareTo(temp) > 0){
if(j == low) break;
}
if(i >= j) break;
exchange(array, i,j);
}
exchange(array,low, j);
return j;
}
public static void exchange(Comparable[] array, int i, int j){
Comparable temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}