刷题笔记:排序算法汇总(2)(选择、归并)

归并排序(二路归并)

思想:利用分治的思想,对待排序的数组划分为一个个的子排序任务,然后合并,再进行排序。具体来说就是:

  • 把长度为n的输入序列分成两个长度为n/2的子序列;
  • 对这两个子序列分别采用归并排序;
  • 将两个排序好的子序列合并成一个最终的排序序列。
  • 将上述步骤递归进行,直至最终得到有序序列。

见下图:
在这里插入图片描述
代码实现如下:

	public static int[] sort(int[] nums){
    
    
        return reSort(nums,0,nums.length-1);
    }

    public static int[] reSort(int[] nums,int low,int high){
    
    
        int mid=(low+high)/2;
        if (low<high){
    
    
            reSort(nums,low,mid);
            reSort(nums,mid+1,high);
            merge(nums,low,mid,high);
        }
        return nums;
    }

    public static void merge(int[] nums,int low,int mid,int high){
    
    
        int[] tmp=new int[high-low+1];

        int i=low;
        int j=mid+1;

        int k=0;

        while (i<=mid&&j<=high){
    
    
            if (nums[i]<nums[j])
                tmp[k++]=nums[i++];
            else
                tmp[k++]=nums[j++];
        }

        while (i<=mid){
    
    
            tmp[k++]=nums[i++];
        }

        while (j<=high){
    
    
            tmp[k++]=nums[j++];
        }

        for (int m=0;m<high-low+1;m++){
    
    
            nums[low+m]=tmp[m];
        }
    }

选择排序

这个排序的算法的思想很简单,每次选出最大或者最小值,放在数组排序部分的最后一个元素的后。
在这里插入图片描述

	public static int[] sort(int[] nums){
    
    
        int pos=0;
        for (int i=0;i<nums.length;i++){
    
    
            int min=Integer.MAX_VALUE;
            for (int j=i;j<nums.length;j++){
    
    
                if (nums[j]<min){
    
    
                    min=nums[j];
                    pos=j;
                }
            }
            nums[pos]=nums[i];
            nums[i]=min;
        }
        return nums;
    }

堆排序

后续添加。。。。。

猜你喜欢

转载自blog.csdn.net/qq_35531985/article/details/112281091