Sort Integers II

题目:

Given an integer array, sort it in ascending order. Use quick sort, merge sort, heap sort or any O(nlogn) algorithm.

分析:

解法:quick sort

public class Solution {
    /**
     * @param A an integer array
     * @return void
     */
    public void quickSort(int[] A, int start, int end) {
        if (start >= end) {
            return;
        }
        int left = start;
        int right = end;
        int pivot = A[start + (end - start) / 2];
        while (left <= right) {
            while (left <= right && A[left] < pivot) {
                left++;
            }
            while (left <= right && A[right] > pivot) {
                right--;
            }
            if (left <= right) {
                int temp = A[left];
                A[left] = A[right];
                A[right] = temp;

                left++;
                right--;
            }
        }
        quickSort(A, start, right);
        quickSort(A, left, end);
    } 

    public void sortIntegers2(int[] A) {
        // Write your code here
        if (A.length <= 1) {
            return;
        }
        quickSort(A, 0, A.length - 1);
    }
}

解法:merge sort

public class Solution {

    public void mergeSort(int[] A, int start, int end, int[] B) {
        if (start >= end) {
            return;
        }
        int mid = start + (end - start) / 2;
        mergeSort(A, start, mid, B);
        mergeSort(A, mid + 1, end, B);
        merge(A, start, mid, end, B);
    } 

    public void merge(int[] A, int start, int mid, int end, int[] B) {
        int left = start;
        int right = mid + 1;
        int index = start;
        while (left <= mid && right <= end) {
            if (A[left] < A[right]) {
                B[index] = A[left];
                index++;
                left++;
            } else {
                B[index] = A[right];
                index++;
                right++;
            }
        }
        while (left <= mid) {
            B[index] = A[left];
            index++;
            left++;
        }
        while (right <= end) {
            B[index] = A[right];
            index++;
            right++;
        }
        for (int i = start; i <= end; i++) {
            A[i] = B[i];
        }
    }

    public void sortIntegers2(int[] A) {
        // Write your code here
        if (A.length <= 1) {
            return;
        }
        int[] B = new int[A.length];
        mergeSort(A, 0, A.length - 1, B);
    }
}

results matching ""

    No results matching ""