图解快数排序法
快速排序图解:
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
==========================================================================================================================
==========================================================================================================================
java 代码的实现:
1 package main.test; 2 3 public class KSSort { 4 public static int Partition(int[] a, int p, int r) { 5 int x = a[r - 1]; 6 int i = p - 1; 7 int temp; 8 for (int j = p; j <= r - 1; j++) { 9 if (a[j - 1] <= x) { 10 // 交换(a[j-1],a[i-1]); 11 i++; 12 temp = a[j - 1]; 13 a[j - 1] = a[i - 1]; 14 a[i - 1] = temp; 15 } 16 } 17 //交换(a[r-1,a[i+1-1]); 18 temp = a[r - 1]; 19 a[r - 1] = a[i + 1 - 1]; 20 a[i + 1 - 1] = temp; 21 return i + 1; 22 } 23 24 25 public static void QuickSort(int[] a,int p,int r){ 26 if(p<r){ 27 int q=Partition(a,p,r); 28 QuickSort(a,p,q-1); 29 QuickSort(a,q+1,r); 30 } 31 } 32 33 static void print(int[] a) { 34 for (int values : a 35 ) { 36 System.out.print(values+" | "); 37 } 38 } 39 40 41 public static void main(String[] args) { 42 int[] a={7,10,3,5,4,6,2,8,1,9}; 43 QuickSort(a,1,10); 44 print(a); 45 46 47 } 48 49 50 }
1 public class QuickSort { 2 public static void quickSort(int[] arr,int low,int high){ 3 int i,j,temp,t; 4 if(low>high){ 5 return; 6 } 7 i=low; 8 j=high; 9 //temp就是基准位 10 temp = arr[low]; 11 12 while (i<j) { 13 //先看右边,依次往左递减 14 while (temp<=arr[j]&&i<j) { 15 j--; 16 } 17 //再看左边,依次往右递增 18 while (temp>=arr[i]&&i<j) { 19 i++; 20 } 21 //如果满足条件则交换 22 if (i<j) { 23 t = arr[j]; 24 arr[j] = arr[i]; 25 arr[i] = t; 26 } 27 28 } 29 //最后将基准为与i和j相等位置的数字交换 30 arr[low] = arr[i]; 31 arr[i] = temp; 32 //递归调用左半数组 33 quickSort(arr, low, j-1); 34 //递归调用右半数组 35 quickSort(arr, j+1, high); 36 } 37 38 39 public static void main(String[] args){ 40 int[] arr = {10,7,2,4,7,62,3,4,2,1,8,9,19}; 41 quickSort(arr, 0, arr.length-1); 42 for (int i = 0; i < arr.length; i++) { 43 System.out.println(arr[i]); 44 } 45 } 46 }