publicclassSelection_sort{ // ---------------------------------------------simple selection sorting publicstaticvoidselectionSort(int[] arr){ for (int i = 0; i < arr.length - 1; i++) { int min = i; for (int j = i + 1; j < arr.length; j++) { if (arr[j] < arr[min]) { min = j; } } int tmp = arr[min]; arr[min] = arr[i]; arr[i] = tmp; } }
// ---------------------------------------------heap sorting publicstaticvoidHeapSort(int[] nums){ // Build heap (rearrange array) int n = nums.length; for (int i = n / 2 - 1; i >= 0; i--){ heapify_recursive(nums, i, n); } // One by one extract an element from heap for (int i = n - 1; i > 0; i--) { // Move current root to end int tmp = nums[0]; nums[0] = nums[i]; nums[i] = tmp; // call max heapify on the reduced heap heapify_recursive(nums, 0, i); } } // To heapify a subtree rooted with node i which is // an index in arr[]. n is size of heap publicstaticvoidheapify_recursive(int[] arr, int i, int n){ int largest = i; // Initialize largest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2
// If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l;
// If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r;
// If largest is not root if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap;
// Recursively heapify the affected sub-tree heapify_recursive(arr, largest, n); } } /* // To heapify a subtree rooted with node i which is // an index in arr[]. n is size of heap public static void HeapAdjust(int[] num, int i, int n) { int tmp = num[i]; // 根据完全二叉树的性质可知道每一个序号对应的子节点以及双亲节点 for (int j = 2 * i + 1; j < n; j = 2 * j + 1) { // j指向数值较大的节点 if (j + 1 < n && num[j] < num[j + 1]) j = j + 1; // 如果调整节点大于其子节点最大的值则无需调整 if (tmp > num[j]) break; // 如果小于则将子节点移动到根节点位置,如果还存在子节点则继续判断调整位置的子节点,准备继续向下 调整节点 num[i] = num[j]; i = j; } // 最后插入数据 num[i] = tmp; }*/ // ********************************************* publicstaticvoidmain(String[] args){ int[] arr1 = new Random().ints(20, 1,100).toArray(); selectionSort(arr1); System.out.println("\nsimple selection sort: "); for (int i : arr1) System.out.print(i+","); System.out.println("\n");
int[] arr2 = new Random().ints(20, 1,100).toArray(); HeapSort(arr2); System.out.println("heapSort: "); for (int i : arr2) System.out.print(i+","); System.out.println("\n"); } }