public class FaskSort {
private static int count0 = 0;
public static void sort(int[] array){
if(array.length > 0){
sort(array, 0, array.length - 1);
}
}
private static void sort(int[] array, int low, int high){
count0++;
int p_pos = low;// 分界索引
int p_voint = array[low];// 基值
int temp;
for (int i = low + 1; i <= high; i++){
if(array[i] < p_voint){
p_pos++;
if(p_pos != i){// 索引相同避免交换
temp = array[p_pos];
array[p_pos] = array[i];
array[i] = temp;
}
}
}
// 把基准值放到排好序的最后位置
if(p_pos != low){
temp = array[p_pos];
array[p_pos] = array[low];
array[low] = temp;
}
if(p_pos - 1 > low){
sort(array, low, p_pos - 1);
}
if(high > p_pos + 1){
sort(array, p_pos + 1, high);
}
}
private static int count1 = 0;
public static void sort1(int[] array){
if(array.length > 0){
sort1(array, 0, array.length - 1);
}
}
private static void sort1(int[] array, int low, int high){
count1++;
int i = low +1;
int j = high;
int key = array[low];
int temp;
while (i < j){
while(i < j && array[i] < key){// i < j时从左往右找大于key的 索引
i++;
}
while(i < j && array[j] > key ){// i < j时从右往左找小于key的 索引
j--;
}
if(i < j){// 然后交换
temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
if (array[i] >= key) {// 由于上面while退出条件的缺陷 进行修正,此时i索引处左边全是小于key
i--;
}
temp = array[i];
array[i] = array[low];
array[low] = temp;
if(i -1 > low){
sort1(array, low, i -1);
}
if(high > i + 1){
sort1(array, i + 1, high);
}
}
private static int count2 = 0;
public static void fastSort(int[] array, int low, int high){
int base = array[low];
int i = low;
int j = high;
int temp;
while(i < j){
while(i < j && array[j] >= base){
j--;
}
while(i < j && array[i] <= base){
i++;
}
if(i < j){
temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
temp = array[i];
array[i] = array[low];
array[low] = temp;
if(low < i - 1){
fastSort(array, low, i - 1);
}
if(i + 1 < high) {
fastSort(array, i + 1, high);
}
}
public static void main(String[] args) {
{
int[] array = {6, 4, 7, 5, 9, 3, 2, 1, 8};
sort(array);
System.out.println(Arrays.toString(array));
System.out.println(count0);
}
{
int[] array1 = {6, 4, 7, 5, 9, 3, 2, 1, 8};
sort1(array1);
System.out.println(Arrays.toString(array1));
System.out.println(count1);
}
{
int[] array2 = {6, 4, 7, 5, 9, 3, 2, 1, 8};
fastSort(array2);
System.out.println(Arrays.toString(array2));
System.out.println(count3);
}
}
}