Friday, May 13, 2022

912. Sort an Array

 一刷

Version #1 Quick sort 

这个写的不好,看下边一个版本

有两个问题

1.不应该选取nums[start] 作为pivot,因为如果原有的nums是descending or ascending order, the time efficiency will be reduced

2.left++和right--的条件应该是大于或者小于

Runtime: 952 ms, faster than 16.06% of Java online submissions for Sort an Array.
Memory Usage: 72.9 MB, less than 17.00% of Java online submissions for Sort an Array.

Version #1 Quick Sort

class Solution {

    public int[] sortArray(int[] nums) {

        // Quick sort

        // Select the 1st element in the array, devide the array by comparing each element with the seleted element

        // start         end

        // nums[i] <= p    nums[i] >= p

        return sortArrayHelper(nums, 0, nums.length - 1);

    }

    //  s             e  r l

    // [0,1,1,1,1,1,1,1,1,6,5]

    private int[] sortArrayHelper(int[] nums, int start, int end) {

        if (start >= end) {

            return nums;

        }

        //                      lr

        // [(1),1,1,1,1,1,1,1,0,6,5]

        int left = start + 1, right = end;

        int p = nums[start];

        while (left <= right) {

            // left is the first character that's larger than p

            while (left <= right && nums[left] <= p) {

                left++;

            }

            while (left <= right && nums[right] >= p) {

                right--;

            }

            if (left <= right) {

                swap(nums, left, right);

                left++;

                right--;

            }

        }

        swap(nums, start, left - 1);

        sortArrayHelper(nums, start, left - 2);

        sortArrayHelper(nums, left, end);

        return nums;

    }

    

    private void swap(int[] nums, int i, int j) {

        int temp = nums[i];

        nums[i] = nums[j];

        nums[j] = temp;

    }

}


Version #1 Quick sort

Optimized version

Using nums[(start + end) / 2] as the pivot

This will improve the speed if the nums are in ascending or descending order

Runtime: 10 ms, faster than 88.81% of Java online submissions for Sort an Array.
Memory Usage: 50.8 MB, less than 97.00% of Java online submissions for Sort an Array.

class Solution {

    public int[] sortArray(int[] nums) {

        // Quick sort

        // Shuffle the array (optional)

        // Partition so that, for some j

        // - entry a[j] is in place

        // - no larger entry to the left of j

        // - no smaller entry to the right of j

        // Sort each piece recursively

        if (nums == null) {

            return null;

        }

        quickSort(nums, 0, nums.length - 1);

        return nums;

    }

    

    // Sort given array from index start to index end

    private void quickSort(int[] nums, int start, int end) {

        if (start >= end) {

            return;

        }

        int pivot = nums[start + (end - start) / 2];

        // partition the subarray between start and end

        // so that all nums <= pivot are on the left, all nums >= pivot are on the right

        int left = start, right = end;

        while (left <= right) {

            while (left <= right && nums[left] < pivot) {

                left++;

            }

            while (left <= right && nums[right] > pivot) {

                right--;

            }

            if (left <= right) {

                // swap nums[left] and nums[right]

                int temp = nums[left];

                nums[left] = nums[right];

                nums[right] = temp;

                left++;

                right--;

            }

        }

        // All nums to the left side of pointer l are smaller than pivot

        // All nums to the right side of pointer r are larger than pivot

        //       l

        //   r

        // 0 1 2 3

        quickSort(nums, start, right);

        quickSort(nums, left, end);

    }

}


Version #2 Merge Sort

每次都new了一个新的result数组,浪费了空间,同时time wasted during the construction of new temporary arrays

下面写了optimized solution

Runtime: 19 ms, faster than 52.47% of Java online submissions for Sort an Array.
Memory Usage: 72.8 MB, less than 17.01% of Java online submissions for Sort an Array.

class Solution {

    public int[] sortArray(int[] nums) {

        // Merge sort

        // Divide nums array from the middle, sort each subarray separately

        // Merge two arrays together

        if (nums == null) {

            return null;

        }

        return mergeSort(nums, 0, nums.length - 1);

    }

    

    private int[] mergeSort(int[] nums, int start, int end) {

        // exit criteria

        if (start > end) {

            return new int[0];

        }

        if (start == end) {

            return new int[]{nums[start]};

        }

        int[] leftNums = mergeSort(nums, start, (start + end) / 2);

        int[] rightNums = mergeSort(nums, (start + end) / 2 + 1, end);

        return merge(leftNums, rightNums);

    }

    

    private int[] merge(int[] nums1, int[] nums2) {

        int[] result = new int[nums1.length + nums2.length];

        int p1 = 0, p2 = 0, pr = 0;

        while (p1 < nums1.length && p2 < nums2.length) {

            if (nums1[p1] <= nums2[p2]) {

                result[pr] = nums1[p1];

                p1++;

                pr++;

            } else {

                result[pr] = nums2[p2];

                p2++;

                pr++;

            }

        }

        while (p1 < nums1.length) {

            result[pr] = nums1[p1];

            pr++;

            p1++;

        }

        while (p2 < nums2.length) {

            result[pr] = nums2[p2];

            pr++;

            p2++;

        }

        return result;

    }

}


Version #2 Merge Sort [Optimized]

To preserve stability, if two keys are equal, we always need to first choose from the left subarray

Runtime: 10 ms, faster than 88.81% of Java online submissions for Sort an Array.
Memory Usage: 51.2 MB, less than 91.77% of Java online submissions for Sort an Array.

class Solution {

    public int[] sortArray(int[] nums) {

        // Merge sort

        // Divide array into two halves

        // Recursively sort each half

        // Merge two halves

        if (nums == null) {

            return null;

        }

        // Create a auxiliary array to temporarily store the subarray

        int[] aux = new int[nums.length];

        quickSort(nums, 0, nums.length - 1, aux);

        return nums;

    }

    

    // quickSort - sort array from index start to index end

    private void quickSort(int[] nums, int start, int end, int[] aux) {

        // base case

        if (start >= end) { // stop when there's less than or equal to one element

            return;

        }

        int mid = start + (end - start) / 2;

        quickSort(nums, start, mid, aux);

        quickSort(nums, mid + 1, end, aux);

        // Optimize - if the largest element in the first half is smaller than the smallest element in the second half, no need to merge since the array is already sorted

        if (nums[mid] < nums[mid + 1]) {

            return;

        }

        merge(nums, start, mid, end, aux);

    }

    

    // merge - merge subarray [start, mid] with subarray [mid + 1, end]

    // Guarantee that the two subarrays are ordered

    private void merge(int[]nums, int start, int mid, int end, int[] aux) {

        // Firstly copy the original array to the auxiliary array

        for (int i = start; i <= end; i++) {

            aux[i] = nums[i];

        }

        // keep 3 pointers, pFirstHalf, pSecondHalf, pResult

        int pFirstHalf = start, pSecondHalf = mid + 1, pResult = start;

        while (pFirstHalf <= mid && pSecondHalf <= end) {

            // If two elements are equal, choose from the firsthalf

            if (aux[pFirstHalf] <= aux[pSecondHalf]) {

                nums[pResult] = aux[pFirstHalf];

                pFirstHalf++;

            } else {

                nums[pResult] = aux[pSecondHalf];

                pSecondHalf++;

            }

            pResult++;

        }

        while (pFirstHalf <= mid) {

            nums[pResult++] = aux[pFirstHalf++];

        }

        while (pSecondHalf <= end) {

            nums[pResult++] = aux[pSecondHalf++];

        }

    }

}

No comments:

Post a Comment