快速排序
import java.util.Arrays; public class Hello { public static void quickSort(int[] arr,int low,int high){ int i,j ,temp,t; if (low > high){ return ; } i = low; j = high; temp = arr[low]; while (i < j){ while(i < j && arr[j] >=temp){ j--; } while(i < j && arr[i] <= temp){ i++; } if (i < j){ t = arr[i]; arr[i] = arr[j]; arr[j] = t; } } // 基准归位 arr[low] = arr[i]; arr[i] = temp; quickSort(arr,low,j-1); quickSort(arr,j+1,high); } public static void main(String[] args){ int[] arr = {10,7,2,4,7,62,3,4,2,1,8,9,19}; quickSort(arr, 0, arr.length-1); System.out.println(Arrays.toString(arr)); } }
import java.util.Arrays; public class Hello { public static void quickSort(int[] arr,int low,int high){ int i,j ,temp,t; if (low > high){ return ; } i = low; j = high; temp = arr[low]; while (i < j){ while(i < j && arr[j] >=temp){ j--; } arr[i] = arr[j]; // arr[i]的值已经被temp保存了, 把右边的值放到arr[i]位置 while(i < j && arr[i] < temp){ i++; } arr[j] = arr[i]; // arr[j]的在上一步已经放到arr[i]里面了 , 覆盖不影响 } // 因为最终 i=j时候退出循环 大于等于 或者小于等于都移动赋值了, 最后这个位置肯定是个坑,把基准填进来就行 arr[i] = temp; quickSort(arr,low,j-1); quickSort(arr,j+1,high); } public static void main(String[] args){ int[] arr = {10,7,2,4,7,10,3,4,2,1,8,9,19}; quickSort(arr, 0, arr.length-1); System.out.println(Arrays.toString(arr)); } }