java排序算法:快速排序

快速排序 

时间复杂度O(nlogn),不稳定。

package com.algorrithms.learn;

/**
 * @program: com.algorrithms.learn
 * @description:
 * @author: liujinghui
 * @create: 2019-02-17 15:16
 **/
public class QuickSort {
    int partion(int num[], int headIndex, int tailIndex)
    {
        //第一个节点选做comparenode,其他节点都会与它进行比较
        //该节点左边的数据都小于该节点
        //该节点右侧的数据都大于该节点
        int compareNode = num[headIndex];
        //crisisPoint : 临界点索引
        //如果第一个节点的大于临界点索引指向的值,临界点索引++,
        //如果第一个节点的小于等于临界点索引指向的值,临界点指针保持不变。
        //因为在临界点之后的值有可能都大于临界点的值。(如果出现小于临界点的值则进行临界点值交换)
        int crisisPoint = headIndex;
        for(int i=headIndex+1;i<=tailIndex;i++){
            if(num[i]<compareNode){
                int temp = num[crisisPoint+1];
                num[crisisPoint+1] = num[i];
                num[i] = temp;
                crisisPoint++;
            }
        }
        //最后要做的就是交换头结点和临界点的值,保证[...]<临界点<[...]
        int temp = num[headIndex];
        num[headIndex] = num[crisisPoint];
        num[crisisPoint] = temp;
        return crisisPoint;
    }
    void quickSort(int num[], int headIndex, int tailIndex)
    {
        //过滤
        if (headIndex < tailIndex) {
            //临界点
            int crisisPoint = partion(num, headIndex, tailIndex);
            quickSort(num, headIndex, crisisPoint - 1);
            quickSort(num, crisisPoint + 1, tailIndex);
        }
    }
    void quickSort(int num[])
    {
        quickSort(num, 0, num.length - 1);
    }

    public static void main(String[] args) {
//        int[] a = new int[]{32,4,5,76,1};
        int[] a = new int[]{32,4,5,76,7,4,546,4435,5634,5654,654,876,8,67,9,43,534,6,554,8,6754,7,4523,4,2156,43,7653,8,7639,4};
        QuickSort quickSort = new QuickSort();
        quickSort.quickSort(a);
        for(int i=0;i<a.length;i++){
            System.out.print(a[i] + " ");
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值