文章目录
- 七、排序算法
- 7.1 常考排序
- 7.1.1 快速排序
- 7.1.2 归并排序
- 7.1.3 堆排序
七、排序算法
7.1 常考排序
7.1.1 快速排序
package com.gyh.reverselinkedlist;import java.util.*;
import java.util.stream.Collectors;
public class Test1 {public static void main(String[] args) {int[] nums = {2};quickSort(nums, 0, nums.length-1,false);Arrays.stream(nums).forEach(System.out::println);}private static void quickSort(int[] nums, int left, int right, boolean isAsc){if(nums == null || nums.length == 1){return;}int pivot = nums[left]; int l = left , h = right;while(l < h){while(l<h && (isAsc == (nums[h] >= pivot))){h--;}nums[l] = nums[h];while(l<h && (isAsc == (nums[l] <= pivot))){l++;}nums[h] = nums[l];}nums[l] = pivot; if(l - 1>left){quickSort(nums, left, l-1, isAsc);}if(h+1<right){quickSort(nums, h+1, right, isAsc);}}}
7.1.2 归并排序
package com.gyh.reverselinkedlist;import java.util.Arrays;
public class Test2 {public static void main(String[] args) {int[] nums = {1,22,13,94,5};divide(nums, new int[nums.length], 0, nums.length-1,false);Arrays.stream(nums).forEach(System.out::println);}private static void divide(int[] nums, int[] temp, int left, int right, boolean isAsc){if(left>=right){return;}int mid = (right+left) / 2;divide(nums, temp, left, mid, isAsc);divide(nums, temp, mid+1, right, isAsc);merge(nums, temp, left, mid+1, right+1, isAsc);}private static void merge(int[] nums, int[] temp, int l, int r, int end, boolean isAsc){int length = 0;int start = l;int mid = r;while(l<mid&&r<end){if(isAsc?nums[l]<=nums[r]:nums[r]<=nums[l]){temp[length++] = nums[l++];}else{temp[length++] = nums[r++];}}while(l<mid) temp[length++] = nums[l++];while(r<end) temp[length++] = nums[r++];length = 0;for(int i = start;i<end;i++){nums[i] = temp[length++];}}
}
7.1.3 堆排序
package com.gyh.reverselinkedlist;import java.util.Arrays;
public class Test3 {public static void main(String[] args) {int[] nums = {10,28,1,5,88,17,2,17};heapSort(nums, false);Arrays.stream(nums).forEach(System.out::println);}private static void heapSort(int[] nums, boolean isAsc){initHeap(nums, isAsc);for(int i = nums.length-1;i>0;i--){int temp = nums[0];nums[0] = nums[i];nums[i] = temp;adjustHeap(nums, 0, i-1, isAsc);}}private static void initHeap(int[] nums, boolean isAsc){for(int i = nums.length/2-1;i>=0;i--){adjustHeap(nums, i, nums.length-1,isAsc);}}private static void adjustHeap(int[] nums, int heapTopIndex, int lastIndex, boolean isAsc){if(heapTopIndex>=lastIndex){return;}int heapTopData = nums[heapTopIndex];for(int i = heapTopIndex*2+1;i<=lastIndex;i=i*2+1){if(i<lastIndex && (isAsc?nums[i+1] > nums[i]:nums[i+1] < nums[i])){i++;}if(isAsc?heapTopData >= nums[i]:heapTopData <= nums[i]){break;}nums[heapTopIndex] = nums[i];heapTopIndex = i;}nums[heapTopIndex] = heapTopData;}
}