转载请注明:
快速排序(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 number int pivot = array[lowerIndex + (higherIndex - lowerIndex) / 2]; // Divide into two arrays while (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的大小是要排序的数组中,元素大小的极值差+1 int 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
视图动画学习算法和数据结构(二)(<Garry进阶(四)>)
原文:http://blog.csdn.net/lrs123123/article/details/43921087