6种排序算法的简洁实现:冒泡、选择、插入、归并、快速、堆(二)

2014-11-24 08:20:09 · 作者: · 浏览: 2
// 重建堆 private static void rebuildHeap(int[] array, int last) { int curIndex = 0; boolean isHeap = false; while (!isHeap) { int leftChildIndex = 2 * curIndex + 1; int rightChildIndex = 2 * curIndex + 2; int maxIndex = curIndex; if (leftChildIndex <= last && array[maxIndex] < array[leftChildIndex]) { maxIndex = leftChildIndex; } if (rightChildIndex <= last && array[maxIndex] < array[rightChildIndex]) { maxIndex = rightChildIndex; } if (maxIndex != curIndex) { swap(array, curIndex, maxIndex); curIndex = maxIndex; } else { isHeap = true; } } } /** * 测试排序算法,比较直观;写单元测试也可,更严谨。 */ public static void main(String[] args) { SortingUtils.debug = true; testBubbleSort(); testSelectionSort(); testInsertionSort(); testQuickSort(); testMergeSort(); testHeapSort(); } // 测试堆排序 private static void testHeapSort() { println("堆排序:"); int[] heapSortArray = { 1, 13, 2, 4, 5, 7 }; quickSort(heapSortArray); print(heapSortArray); } // 测试归并排序 private static void testMergeSort() { println("归并排序:"); int[] mergeSortArray = { 1, 13, 2, 4, 5, 7 }; mergeSort(mergeSortArray); print(mergeSortArray); } // 测试快速排序 private static void testQuickSort() { println("快速排序:"); int[] quickSortArray = { 1, 13, 2, 4, 5, 7 }; quickSort(quickSortArray); print(quickSortArray); } // 测试插入排序 private static void testInsertionSort() { println("插入排序:"); int[] insertionSortArray = { 1, 13, 2, 4, 5, 7 }; insertionSort(insertionSortArray); print(insertionSortArray); } // 测试选择排序 private static void testSelectionSort() { println("选择排序:"); int[] selectionSortArray = { 1, 13, 2, 4, 5, 7 }; selectionSort(selectionSortArray); print(selectionSortArray); } // 测试冒泡排序 private static void testBubbleSort() { println("冒泡排序:"); int[] bubbleSortArray = { 1, 13, 2, 4, 5, 7 }; bubbleSort(bubbleSortArray); print(bubbleSortArray); } }


运行结果

冒泡排序:
[debug]1 2 4 5 7 13
[debug]1 2 4 5 7 13
1 2 4 5 7 13
选择排序:
[debug]1 7 2 4 5 13
[debug]1 5 2 4 7 13
[debug]1 4 2 5 7 13
[debug]1 2 4 5 7 13
[debug]1 2 4 5 7 13
1 2 4 5 7 13
插入排序:
[debug]1 13 2 4 5 7
[debug]1 2 13 4 5 7
[debug]1 2 4 13 5 7
[debug]1 2 4 5 13 7
[debug]1 2 4 5 7 13
1 2 4 5 7 13
快速排序:
[debug]1 2 13 4 5 7
[debug]1 2 4 13 5 7
[debug]1 2 4 5 13 7
[debug]1 2 4 5 7 13
[debug]1 2 4 5 7 13
1 2 4 5 7 13
归并排序:
1 2 4 5 7 13
堆排序:
[debug]1 2 13 4 5 7
[debug]1 2 4 13 5 7
[debug]1 2 4 5 13 7
[debug]1 2 4 5 7 13
[debug]1 2 4 5 7 13
1 2 4 5 7 13

原文链接:http://FansUnion.cn/articles/3349(小雷网-FansUnion.cn)