手写快排/归并排序

class Solution {
    public int[] sortArray(int[] nums) {
        QuickSort(nums, 0, nums.length - 1);
        return nums;
    }

    void QuickSort(int[] nums, int left, int right) {
        if (left < right) {
            //返回基准位置
            int pos = position(nums, left, right);
            QuickSort(nums, left, pos - 1);
            QuickSort(nums, pos + 1, right);
        }
    }

    int position(int[] nums, int left, int right) {
        //在[left, right]之间随机选择一个下标作为基准
        int p = new Random().nextInt(right - left + 1) + left;
        //将基准暂时放到left位置上,便于后续遍历
        swap(nums, left, p);
        int i = left + 1;
        int j = right;
        while (true) {
            while (i <= right && nums[i] < nums[left])
                i++;
            while (j > left && nums[j] > nums[left])
                j--;
            if (i > j)
                break;
            swap(nums, i, j);
            i++;
            j--;
        }
        swap(nums, left, j);
        return j;
    }

    void swap(int[] nums, int a, int b) {
        int temp = nums[a];
        nums[a] = nums[b];
        nums[b] = temp;
    }

}
快速排序
public class Solution {

    public int[] MySort (int[] arr) {
        // write code here
        merge(arr, 0, arr.length - 1);
        return arr;
    }
    
    //
    void merge(int[] arr, int left, int right) {
       if (left < right) {
           int mid = (left + right) / 2;
           merge(arr, left, mid);
           merge(arr, mid + 1, right);
           //
           mergesort(arr, left, mid, right);
       }
    }
    
    //
    void mergesort(int[] arr, int left, int mid, int right) {
        int i = left, j = mid + 1;
        //辅助数组
        int[] temp = new int[right - left + 1];
        int index = 0;
        while (i <= mid && j <= right) {
            if (arr[i] <= arr[j]) {
                temp[index++] = arr[i++];
            } else {
                temp[index++] = arr[j++];
            }
        }
        while (i <= mid) {
            temp[index++] = arr[i++];
        }
        while (j <= right) {
            temp[index++] = arr[j++];
        }
        for (i = 0; i < index; i++) {
            arr[left++] = temp[i];
        }
    }
}
归并排序

 

posted @ 2021-01-30 14:39  缘未到  阅读(61)  评论(0编辑  收藏  举报