1. 程式人生 > 實用技巧 >JAVA 排序總結

JAVA 排序總結

快速排序

時間複雜度:\(O(n\log n)\)

空間複雜度:\(O(\log n)\)

不穩定

public static void sortQuick(int[] arr,int l,int r) {
    if(l >= r) return;
    int base = arr[l + r >> 1];
    // 防止越界,向兩邊擴
    int left = l - 1,right = r + 1;
    while(left < right) {
        do left ++;while (arr[left] < base);
        do right --;while (arr[right] > base);
        if(left < right) swap(arr,left,right);
    }
    // l left
    // left - 1,r
    sortQuick(arr,l,right);
    sortQuick(arr,right + 1,r);
}
public static void swap(int[] arr,int x,int y) {
    int t = arr[x];
    arr[x] = arr[y];
    arr[y] = t;
}

歸併排序

時間複雜度:\(O(n\log n)\)

空間複雜度:\(O(n)\)

穩定

private static int[] tmp;
private static int[] arr;
public static void mergeSort(int l,int r) {
    if(l >= r) return;
    int mid = l + r >> 1;
    mergeSort(l,mid);
    mergeSort(mid + 1,r);
    int i = l,j = mid + 1,k = 0;
    while(i <= mid && j <= r) {
        if(arr[i] <= arr[j]) tmp[k ++] = arr[i ++];
        else tmp[k ++] = arr[j ++];
    }
    while (i <= mid) tmp[k ++] = arr[i ++];
    while (j <= r) tmp[k ++] = arr[j ++];
    for(i = l,j = 0;i <= r; ++i, ++j) arr[i] = tmp[j];
}

堆排序

時間複雜度:\(O(n\log n)\)

空間複雜度:\(O(n)\)

穩定

package code;

public class HeapSort {
    private static int[] arr = new int[]{-1,10,22,55,0,-2,100};
    private static int[] heap;
    private static int heapSize = 0;
    public static void main(String[] args) {
        heap = new int[arr.length + 1];
        heapSize = arr.length;
        for(int i = 0;i < arr.length; ++i) {
            heap[i + 1] = arr[i];
        }
        heapSort();
        int cnt = heapSize;
        for(int i = 0;i < cnt; ++i) {
            System.out.println(heap[1]);
            heap[1] = heap[heapSize];
            heapSize--;
            heapDown(1);
        }
    }
    public static void swap(int[] arr,int x,int y) {
        int t = arr[x];
        arr[x] = arr[y];
        arr[y] = t;
    }
    public static void heapDown(int u) {
        int t = u;
        if(u * 2 <= heapSize && heap[u * 2] < heap[t]) t = u * 2;
        if(u * 2 + 1 <= heapSize && heap[u * 2 + 1] < heap[t]) t = u * 2 + 1;
        if(u != t) {
            swap(heap,u,t);
            heapDown(t);
        }
    }
    public static void heapSort() {
        for(int i = heapSize / 2;i > 0; --i) {
            heapDown(i);
        }
    }
}