快速排序和归并排序

本文详细介绍了两种经典的排序算法:归并排序和快速排序。通过具体的Java代码实现了这两种算法,并展示了如何对一个整数数组进行排序。归并排序采用分治策略,将数组分为两部分,递归地对每一部分进行排序,然后将两个已排序的部分合并成一个整体。快速排序同样采用分治策略,选择一个基准元素,将数组分为小于和大于基准的两部分,递归地对这两部分进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class test {
    public void mergesort(int[] nums,int low,int high)
    {
       int[] temp=new int[nums.length];
       if(low<high)
       {
           //System.out.println("!!!!!!!!!!!!!");
           int mid=(low+high)/2;
           mergesort(nums,low,mid);
           mergesort(nums,mid+1,high);
           merge(nums,low,high,mid,temp);
       }

    }
    public void merge(int[] nums, int low,int high,int mid,int []temp)
    {
        for(int i=low;i<=high;i++)
        {
            temp[i]=nums[i];
        }
        int k=low;int i=low;int j=mid+1;
        while(i<=mid&&j<=high)
        {
            if(temp[i]<=temp[j])
            {
                nums[k++]=temp[i++];
            }
            else
            {
                nums[k++]=temp[j++];
            }

        }
        while(i<=mid)nums[k++]=temp[i++];
        while(j<=high)nums[k++]=temp[j++];

    }
    public void selesort(int [] nums)
    {
        sort(nums,0,nums.length-1);
    }
    public void sort(int[] nums,int low,int high)
    {
        int p=partition(nums,low,high);
        if(low<high)
        {
            sort(nums,low,p-1);
            sort(nums,p+1,high);
        }

    }
    public int partition(int[] nums,int low,int high)
    {
        int privot=nums[low];
        while(low<high)
        {
            while(low<high&&nums[high]>=privot) --high;
            if(nums[high]<privot) nums[low++]=nums[high];
            while(low<high&&nums[low]<=privot) ++low;
            if(nums[low]>privot) nums[high--]=nums[low];
        }
        nums[low]=privot;
        return low;
    }

    public static void main(String[] args) {
        test t=new test();
        int[] nms=new int[]{4,2,1,6,3,6,0,-5,1,1};
        t.mergesort(nms,0,9);
        for(int i=0;i<nms.length;i++)
        {
            System.out.println(nms[i]);
        }


    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值