• java 归并排序与快速排序


    归并排序

    private static void merge(int[] nums, int[] tempArray, int leftPos, int rightPos, int rightEnd) {
        int leftEnd = rightPos - 1;
        int currPos = leftPos;
        int allNum = rightEnd - leftPos + 1;
        while (leftPos <= leftEnd && rightPos <= rightEnd) {
            if (nums[leftPos] <= nums[rightPos]) tempArray[currPos ++] = nums[leftPos ++];
            else tempArray[currPos ++] = nums[rightPos ++];
        }
        while (leftPos <= leftEnd) tempArray[currPos ++] = nums[leftPos ++];
        while (rightPos <= rightEnd) tempArray[currPos ++] = nums[rightPos ++];
        for (int i = 0; i < allNum; i ++) {
            nums[rightEnd] = tempArray[rightEnd];
            rightEnd --;
        }
    }
    
    private static void mergeSort(int[] nums, int[] temp, int left, int right) {
        if (left < right) {
            int mid = (left + right) / 2;
            mergeSort(nums, temp, left, mid);
            mergeSort(nums, temp, mid + 1, right);
            merge(nums, temp, left, mid + 1, right);
        }
    }
    
    public static void mergeSort(int[] nums) {
        int length = nums.length;
        int[] tempArray = new int[length];
        mergeSort(nums, tempArray, 0, length - 1);
    }
    

    快速排序

    public static void swap(int[] nums, int indexA, int indexB) {
        int temp = nums[indexA];
        nums[indexA] = nums[indexB];
        nums[indexB] = temp;
    }
    
    public static void MyQuickSort(int[] nums) {
        MyQuickSort(nums, 0, nums.length - 1);
    }
    
    private static void MyQuickSort(int[] nums, int start, int end) {
        if (start == end) return;
        int pivotIndex = partition(nums, start, end);
        if (start < pivotIndex) MyQuickSort(nums, start, pivotIndex - 1);
        if (end > pivotIndex) MyQuickSort(nums, pivotIndex + 1, end);
    }
    
    private static int partition(int[] nums, int start, int end) {
        if (start == end) return start;
        int pivotIndex = new Random().nextInt(end - start + 1) + start;
        int pivot = nums[pivotIndex];
        swap(nums, pivotIndex, end);
        int left = start - 1, right = end;
        while (true) {
            if (left < end) while (nums[++left] < pivot) {if (left == end) break;}
            if (right > start) while (nums[--right] > pivot) {if (right == start) break;}
            if (left < right) swap(nums, left, right);
            else break;
        }
        swap(nums, left, end);
        return left;
    }
    
  • 相关阅读:
    @Autowired和@Resource注解的注入顺序
    八大排序算法(Java实现)+ 自制动画
    一文秒杀三个经典面试求和问题
    这篇文章,或许对还在上学的你,有一些帮助
    得了,一文把前缀和给扒的干干净净了。
    BF,BM,KMP,就这?
    那个贼贵的比特币到底是什么原理?
    小样?别以为你穿了几个马甲就不认得你是二分法!
    面试前必知必会的二分查找及其变种
    Vue.js 官方示例初探
  • 原文地址:https://www.cnblogs.com/liulaolaiu/p/11744370.html
Copyright © 2020-2023  润新知