java实现常见排序算法

//快速排序
public static void Quick(int[] nums, int start, int end){
        if(start > end){
            return;
        }
        int i = start,j = end;
        int e = nums[i];
        while (i < j){
            while(i < j && nums[j] >= e){
                j--;
            }
            nums[i] = nums[j];
            while(i < j && nums[i] <= e){
                i++;
            }
            nums[j] = nums[i];
        }
        nums[i] = e;
        Quick(nums,start,i - 1);
        Quick(nums, i + 1, end);
    }



    //归并排序
    public static void MergeSort(int[] nums, int start, int end){

        if(start >= end){
            return;
        }
        //divide
        int mid = (start + end) / 2;
        MergeSort(nums, start, mid);
        MergeSort(nums, mid + 1, end);
        //conquer
        Merge(nums, start, mid, end);

    }
    public static void Merge(int[] nums, int start, int mid, int end){
        int i = start;
        int j = mid + 1;
        int[] temp = new int[end - start + 1];
        int p = 0;  //指向temp数组的待插入位置
        while (i <= mid && j <= end){
            if(nums[i] <= nums[j]){
                temp[p] = nums[i];
                i++;
                p++;
            }else{
                temp[p] = nums[j];
                j++;
                p++;
            }
        }
        while(i <= mid){
            temp[p] = nums[i];
            i++;
            p++;
        }
        while(j <= end){
            temp[p] = nums[j];
            j++;
            p++;
        }
        for (int k = start, l = 0; k <= end; k++,l++) {
            nums[k] = temp[l];
        }

    }

    //直接插入排序
    public static void InsertionSort(int[] nums){
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            for (int j = i; j > 0; j--) {
                if(nums[j] < nums[j - 1]){
                    int temp = nums[j];
                    nums[j] = nums[j -1];
                    nums[j - 1] = temp;
                }
            }

        }
    }

    //冒泡排序
    public static void BubbleSort(int[] nums){
        int len = nums.length;
        for (int i = len - 1; i > 0; i--) {
            for (int j = 0; j < i ; j++) {
                if(nums[j] > nums[j + 1]){
                    int temp = nums[j];
                    nums[j] = nums[j + 1];
                    nums[j + 1] = temp;
                }
            }

        }
    }

    //简单选择
    public static void SelectionSort(int[] nums){

        int len = nums.length;
        for (int i = 0; i < len - 1; i++) {
            int p = i;
            for (int j = i; j < len; j++) {
                if(nums[j] < nums[p]){
                    p = j;
                }
            }
            int temp = nums[i];
            nums[i] = nums[p];
            nums[p] = temp;

        }

    }

 

posted @ 2021-04-19 14:43  三十五画生  阅读(45)  评论(0编辑  收藏  举报