package Sort;
/**
* 快速排序 1.当前数组拿到第一个数作为标准
* 2.从前往后,从后往前,两个指针扫相对着往后扫描 当左往右的大于标准,右往左的小于标准,交换当右指针索引小于左指针,将当前右指针指向的数和标准进行交换
* 3.当前标准找到了正确位置,其他的数划分成两个子数组递归排序
*
* 例
* 第一次交换 27 99(i) 0 8 13 64 86 16 7 10 88 25(j) 90
* 第二次交换 27 25 0 8 13 64(i) 8616 7 10(j) 88 99 90
* 第三次交换 27 25 0 8 13 10 86(i) 16 7(j) 64 88 99 90
* 第四次交换 27 25 0 8 13 10 7 16(j) 86(i) 64 88 99 90
* 划分 16 25 0 8 13 10 7 27 86 64 88 99 90
*
* @author lucky-freya
*
*/
public class QuickSort {
public int partition(int[]array,int startIndex,int endIndex){
int x = array[startIndex];
int i = startIndex + 1;
int j = endIndex;
while(true){
//判断指针移位
while(i<= endIndex && array[i] <= x){
i++;
}
while(j>=0 && array[j]>x){
j--;
}
// 交换
if(i<j){
int swap = array[i];
array[i] = array[j];
array[j] = swap;
}else{
return j;
}
}
}
public void quickSort(int[]array,int startIndex,int endIndex){
if (startIndex >= endIndex){
return;
}
int index = partition(array,startIndex,endIndex);
//交换
int swap = array[startIndex];
array[startIndex] = array[index];
array[index] = swap;
quickSort(array,startIndex,index - 1);
quickSort(array,index + 1,endIndex);
}
public static void main(String args){
QuickSort sort = new QuickSort();
int[] array = new int[]{27,99,0,8,13,64,86,16,7,10,29,299};
sort.quickSort(array, 0, 11);
for(int i = 0;i<array.length;i++){
System.out.println(array[i]);
}
}
}
/**
* 快速排序 1.当前数组拿到第一个数作为标准
* 2.从前往后,从后往前,两个指针扫相对着往后扫描 当左往右的大于标准,右往左的小于标准,交换当右指针索引小于左指针,将当前右指针指向的数和标准进行交换
* 3.当前标准找到了正确位置,其他的数划分成两个子数组递归排序
*
* 例
* 第一次交换 27 99(i) 0 8 13 64 86 16 7 10 88 25(j) 90
* 第二次交换 27 25 0 8 13 64(i) 8616 7 10(j) 88 99 90
* 第三次交换 27 25 0 8 13 10 86(i) 16 7(j) 64 88 99 90
* 第四次交换 27 25 0 8 13 10 7 16(j) 86(i) 64 88 99 90
* 划分 16 25 0 8 13 10 7 27 86 64 88 99 90
*
* @author lucky-freya
*
*/
public class QuickSort {
public int partition(int[]array,int startIndex,int endIndex){
int x = array[startIndex];
int i = startIndex + 1;
int j = endIndex;
while(true){
//判断指针移位
while(i<= endIndex && array[i] <= x){
i++;
}
while(j>=0 && array[j]>x){
j--;
}
// 交换
if(i<j){
int swap = array[i];
array[i] = array[j];
array[j] = swap;
}else{
return j;
}
}
}
public void quickSort(int[]array,int startIndex,int endIndex){
if (startIndex >= endIndex){
return;
}
int index = partition(array,startIndex,endIndex);
//交换
int swap = array[startIndex];
array[startIndex] = array[index];
array[index] = swap;
quickSort(array,startIndex,index - 1);
quickSort(array,index + 1,endIndex);
}
public static void main(String args){
QuickSort sort = new QuickSort();
int[] array = new int[]{27,99,0,8,13,64,86,16,7,10,29,299};
sort.quickSort(array, 0, 11);
for(int i = 0;i<array.length;i++){
System.out.println(array[i]);
}
}
}