工作中用了排序,复习一下。
一、快速排序
快速排序算法有个很好的视频讲解,讲的非常好(比我说的好)推荐给大家:
https://www.youtube.com/watch?v=Vs4SYLLEeI0
根据视频,自己写了下面的快排算法实现。
1 import java.util.Arrays; 2 3 public class QuickSortDemo { 4 5 public static void main(String[] args) { 6 int[] a = {100,53,75,23,47,51,99,80,3,59,30,90,2,52,54}; 7 System.out.println("before sorting, array a is :" + Arrays.toString(a)); 8 System.out.println("------------------------------------------------------------------------------"); 9 sort(a, 0, a.length-1); 10 System.out.println("after sorting, array a is :" + Arrays.toString(a)); 11 } 12 13 private static void sort(int[] a2, int low, int high) { 14 15 // 迭代终止条件 16 if(low>high) { 17 return; 18 } 19 int i = low; 20 int j = high; 21 int midValue = a2[low]; 22 while(i<j) { 23 while(i<j && a2[j] > midValue) { 24 j--; 25 } 26 while(i<j && a2[i] <= midValue) { 27 i++; 28 } 29 if(i<j) { 30 int temp = a2[j]; 31 a2[j] = a2[i]; 32 a2[i] = temp; 33 } 34 } 35 int p = a2[i]; 36 a2[i] = a2[low]; 37 a2[low] = p; 38 // 对左边的数快排 39 sort(a2, low, i-1); 40 // 对右边的数快排 41 sort(a2, i+1, high); 42 } 43 44 45 }