程序员

[算法] - NlogN排序算法

2021-01-29  本文已影响0人  夹胡碰

一、归并排序算法

public class MergeSort {

    public static void mergeSort(int[] arr, int l, int r){
        if(l >= r){
            return;
        }

        int mid = (l + r) / 2;
        mergeSort(arr, l, mid);
        mergeSort(arr, mid+1, r);
        merge(arr, l, mid, r);
    }

    public static void merge(int[] arr, int l, int m, int r){
        int[] tmp = new int[r - l + 1];
        for (int i = 0;i<tmp.length;i++) {
            tmp[i] = arr[l + i];
        }
        int i = l,j = m + 1;
        for(int k = l; k <= r; k++){

            if(i > m){
                arr[k] = tmp[j++ - l];
            } else if(j > r){
                arr[k] = tmp[i++ - l];
            } else if(tmp[i - l] > tmp[j - l]){
                arr[k] = tmp[i++ - l];
            } else {
                arr[k] = tmp[j++ - l];
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {2,4,5,3,1,8,1,4,3};
        mergeSort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }
}

二、快速排序

public class QuickSort {

    public static void quickSort(int[] arr, int l, int r){
        if(l >= r){
            return;
        }

        int p = partition(arr, l, r);
        quickSort(arr, l, p - 1);
        quickSort(arr, p + 1, r);
    }

    public static int partition(int[] arr, int l, int r){
        int tmp = arr[l];

        int j = l;
        for(int i = l + 1; i <= r; i++){
            if(arr[i] < tmp){
                swap(arr, ++j , i);
            }
        }

        swap(arr, l, j);
        return j;
    }

    private static void swap(int[] arr, int s, int d){
        int tmp = arr[s];
        arr[s] = arr[d];
        arr[d] = tmp;
    }

    public static void main(String[] args) {
        int[] arr = {2,4,5,3,1,8,1,4,3};
        quickSort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }
}
上一篇下一篇

猜你喜欢

热点阅读