排序算法总结

本文深入探讨了插入排序、选择排序、归并排序、快速排序及堆排序的实现原理与代码细节,为读者提供了全面的排序算法知识。

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

插入排序

public void insertSort(int []a){
            if(a!=null)
            {int temp;
                for(int i=1;i<a.length;i++){
                    temp = a[i];
                    int j=i;

                    while(j>0&&a[j-1]>temp){
                        a[j]=a[j-1];
                        j--;

                        a[j] = temp;}
                }
            }
        }

选择排序

public void selectSort(int []a){
            int flag,temp;
            for(int i=0;i<a.length;i++){
                temp = a[i];
                flag=i;
                for(int j=i+1;j<a.length;j++){
                    if(a[j]<temp){
                        temp = a[j];
                        flag = j;
                    }
                }
                if(flag!=i){
                    a[flag] = a[i];
                    a[i] = temp;}
            }
        }

归并排序

public void mergeSort(int[] nums,int start,int end){
        if(start==end) return;
        int mid = (start+end)/2;
        mergeSort(nums,start,mid);
        quickSort(nums,mid+1,end);
        int[] temp = new int[end-start+1];
        int i =0,j=mid+1,k=0;
        while(i<=mid&&j<=end)
            nums[k++] = nums[i]>nums[j]?nums[j++]:nums[i++];
        while(i<=mid) nums[k++] = nums[i++];
        while(j<=end) nums[k++] = nums[j++];
        System.arraycopy(temp,0,nums,start,end-start+1);
    }

快速排序

public void quickSort(int[] nums,int start,int end){
        if(start>end) return ;
        int i=start,j=end;
        int temp = nums[i];
        while(i<j){
            while(i<j&&nums[j]>temp){
                j--;
            }
            if(i<j) nums[i++] = nums[j];
            while(i<j&&nums[i]<temp){
                i++;
            }
            if(i<j) nums[j--] = nums[i];
        }
        nums[i] = temp;
        quickSort(nums,start,i-1);
        quickSort(nums,i+1,end);
    }

堆排序

public void initHeap(int[] nums,int pos,int len){
        int temp;
        int child;
        for(temp = nums[pos];2*pos+1<=len;pos = child){
            child = 2*pos+1;
            if(child<len&&nums[child]<nums[child+1])
                child++;
            if(temp<nums[child]){
                nums[pos] = nums[child];
            }else{
                break;
            }
        }
        nums[pos] = temp;
    }
    public void heapSort(int[] nums){
        int len = nums.length;
        for (int i = len/2; i >=0 ; i--) {
            initHeap(nums,i,len-1);
        }
        for(int j=len-1;j>=0;j--){
            int temp = nums[0];
            nums[0] = nums[j];
            nums[j] = temp;
            initHeap(nums,0,j-1);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值