讲解快排思路比较好的文章链接
快速排序—(面试碰到过好几次)
最通俗易懂的快速排序算法详解
代码
递归
package quicksort;
import java.util.Arrays;
public class QuickSortDiGui {
public static int getPartion(int[] arr, int low, int high) {
int partion = low;
if(low >= high) {
return partion;
}
int temp = arr[low];
while(low<high) {
while(arr[high]>=temp && low<high) {
high--;
}
if(low<high) {
arr[low] = arr[high];
}
while(arr[low]<=temp && low<high) {
low++;
}
if(low<high) {
arr[high] = arr[low];
}
}
arr[low] = temp;
partion = low;
return partion;
}
public static void quickSort(int[] arr, int low, int high) {
if(arr == null || arr.length == 0) {
return;
}
if(low>=high) {
return;
}
int partion = getPartion(arr, low, high);
if(partion > low+1) {
quickSort(arr, low, partion-1);
}
if(partion < high-1) {
quickSort(arr, partion+1, high);
}
}
public static void doQuickSort(int[] arr) {
quickSort(arr, 0, arr.length-1);
}
public static void main(String[] args) {
int[] arr = {3,1,2,4,6,7,5,3,41,10};
doQuickSort(arr);
System.out.println(Arrays.toString(arr));
}
}
非递归
package quicksort;
import java.util.Arrays;
import java.util.Stack;
public class QuickSortFeiDiGui {
public static int getPartion(int[] arr, int low, int high) {
int partion = low;
if(low >= high) {
return partion;
}
int temp = arr[low];
while(low<high) {
while(arr[high]>=temp && low<high) {
high--;
}
if(low<high) {
arr[low] = arr[high];
}
while(arr[low]<=temp && low<high) {
low++;
}
if(low<high) {
arr[high] = arr[low];
}
}
arr[low] = temp;
partion = low;
return partion;
}
public static void quickSort(int[] arr, int low, int high) {
if(arr == null || arr.length == 0) {
return;
}
if(low>=high) {
return;
}
Stack<Integer> lowHighStack = new Stack<>();
lowHighStack.push(low);
lowHighStack.push(high);
while(lowHighStack.size() > 0) {
high = lowHighStack.pop();
low = lowHighStack.pop();
int partion = getPartion(arr, low, high);
if(partion > low + 1) {
lowHighStack.push(low);
lowHighStack.push(partion - 1);
}
if(partion < high - 1) {
lowHighStack.push(partion+1);
lowHighStack.push(high);
}
}
}
public static void doQuickSort(int[] arr) {
quickSort(arr, 0, arr.length-1);
}
public static void main(String[] args) {
int[] arr = {3,1,2,4,6,7,5,3,41,10};
doQuickSort(arr);
System.out.println(Arrays.toString(arr));
}
}