視圖動畫學習演算法和資料結構(二)(<Garry進階(四)>),garry進階
轉載請註明:
接視圖動畫學習演算法和資料結構(不定期更新)()
快速排序(QuickSort)
動畫示範:
java代碼:
public class QuickSort {private int array[];private int length;public void sort(int[] inputArr) {if (inputArr == null || inputArr.length == 0) {return;}this.array = inputArr;length = inputArr.length;quickSort(0, length - 1);}private void quickSort(int lowerIndex, int higherIndex) {int i = lowerIndex;int j = higherIndex;// calculate pivot number, I am taking pivot as middle index numberint pivot = array[lowerIndex + (higherIndex - lowerIndex) / 2];// Divide into two arrayswhile (i <= j) {while (array[i] < pivot) {i++;}while (array[j] > pivot) {j--;}if (i <= j) {exchangeNumbers(i, j);// move index to next position on both sides i++;j--;}}//調用QuickSort方法if (lowerIndex < j)quickSort(lowerIndex, j);if (i < higherIndex)quickSort(i, higherIndex);}private void exchangeNumbers(int i, int j) {int temp = array[i];array[i] = array[j];array[j] = temp;}public static void main(String a[]) {QuickSort sorter = new QuickSort();int[] input = { 3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48};sorter.sort(input);for (int i : input) {System.out.print(i+", ");}}}
編譯結果:
計數排序(CountingSort)
動畫示範:
java代碼:
public class CountingSort {public static void main(String []args){//排序的數組int a[] = {6,3,1,2,5,7,8,2,1,2,9,5};int b[] = countSort(a);for(int i : b){System.out.print(i + " ");}}public static int[] countSort(int []a){int b[] = new int[a.length];int max = a[0], min = a[0];for(int i : a){if(i > max){max = i;}if(i < min){min = i;}}//這裡k的大小是要排序的數組中,元素大小的極值差+1int k = max - min + 1;int c[] = new int[k];for(int i = 0; i < a.length; ++i){c[a[i]-min] += 1;//最佳化過的地方,減小了數組c的大小}for(int i = 1; i < c.length; ++i){c[i] = c[i] + c[i-1];}for(int i = a.length-1; i >= 0; --i){b[--c[a[i]-min]] = a[i];//按存取的方式取出c的元素}return b;}}
編譯結果:
基數排序(Radix Sort)
動畫示範:
java代碼待整理
//2015-2-24