希尔排序,堆排序,快速排序

1.希尔排序

插入排序的改进算法,不稳定的排序算法,空间复杂度为O(1)

    public static void shellSort(int a[]){
        int k=a.length;
        int temp;
        while (k>1) {
            k=(k+1)/2;
            for (int i = 0; i < a.length-k; i++) {
                if (a[i]>a[i+k]) {
                    temp=a[i];
                    a[i]=a[i+k];
                    a[i+k]=temp;
                }
            }
        }
    }

2.快速排序

冒泡排序的改进算法,不稳定的排序算法
空间复杂度在O(log2n)和O(n)之间
时间复杂度在O(n)和O(n2)之间,平均时间复杂度为O(nlog2n),而当数组初始有序的条件下,快速排序会退化为冒泡排序

//一趟快速排序算法
public static int partition(int i,int j){
        int temp=a[i];
        while (j>i) {
            while (temp<=a[j]&&j>i) {
                j--;
            }
            if (j>i) {
                a[i]=a[j];
                i++;
            }
            while (temp>=a[i]&&j>i) {
            //写temp>=a[i],将i误写成了j浪费了大量时间排错
                i++;
            }
            if (j>i) {
                a[j]=a[i];
                j--;
            }
        }
        a[i]=temp;
        return i;
    }
    //static int count=0;
    //递归调用partition()函数,进行多趟排序直至整个数组有序
    public static void  qSort(int low,int high){
        if (high>low) {
            int i=partition(low, high);
            qSort(low, i-1);
            qSort(i+1, high);
            //System.out.print(++count);
        }
    }
    public static void quickSort(int []a){
        qSort(0, a.length-1);
    }

3.堆排序

树形排序的改进型排序算法,不稳定的排序算法
空间复杂度O(1)
时间复杂度O(nlog2n)

    public static void shift(int low,int high){
        int i=low;
        int j=2*i+1;
        int temp=a[i];
        while (j<high) {
            if (j<high-1&&a[j]>a[j+1]) {
                j++;
            }
            if (a[i]>a[j]) {
                a[i]=a[j];
                i=j;
                j=2*i+1;
            }else {
                j=high+1;
            }
        }
        a[i]=temp;
    }
    public static void heapSort(){
        int len=a.length;
        int temp;
        //初始化堆
        for (int i=len/2-1;i>=0;i--) {
            shift(i, len);
        }
        //将最小关键字值交换到后面,再调整堆
        for (int i=len-1;i>0;i--) {
            temp=a[0];
            a[0]=a[i];
            a[i]=temp;
            shift(0, i);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值