Java中的快速排序算法

快速排序(也称为分区交换排序)是一种高效的分而治之排序算法。 可以利用循环或递归来实现该算法。 该算法就地执行排序。 快速排序是一种比较排序,这意味着它可以对定义了“小于”关系的任何类型的项目进行排序。

该算法将数组分为两个较小的子数组。 要将算法分为两个数组,请选择数组中的枢轴或元素。 分区阶段包括对数组重新排序,以使所有值小于枢轴的元素都在枢轴之前,而所有值大于枢轴的元素都在其之后。 在分区阶段之后,枢轴处于其最终位置。 枢轴在逻辑上将原始数组分为两个子数组。 然后,“快速排序”算法通过选择新的枢轴点对子数组进行递归排序,并相应地移动值。 每个元素都将被选作枢轴,并将被放置在正确的位置。

Algorithm Classification

下表包含有关快速排序算法分析的信息。 它根据时间复杂度以及空间复杂度定义了最坏,平均和最佳情况。

属性值类排序算法类ification内部,原位,不稳定算法数据结构数组时间复杂度:最佳Ω(n log(n))时间复杂度:平均值Θ(n log(n))时间复杂度:最差上2)空间复杂性:最差上 log(n))

Please use the following link for an explanation on Big-O notation and what is good, fair and bad.

Quick Sort In Java

public final class QuickSort {

    public void sort(int[] collection) {
        if (collection != null) {
            quickSort(collection, 0, collection.length-1);
        } else {
            throw new IllegalArgumentException("Input paramenter for array to sort is null.");
        }
    } 

    private void quickSort(int[] collection, int firstPosition, int lastPosition) {
        if (firstPosition >= lastPosition) {
            return;
        } else {            
            int pivotIndex = partition(collection, firstPosition, lastPosition);
            quickSort(collection, firstPosition, pivotIndex-1);
            quickSort(collection, pivotIndex+1, lastPosition);
        }       
    } 

    private int partition(int[] collection, int firstPosition, int lastPosition) {  
        int pivotIndex = selectPivot(firstPosition, lastPosition);
        swap (collection, pivotIndex, lastPosition);
        int store = firstPosition;
        pivotIndex = lastPosition;
        for (int i = firstPosition; i <= lastPosition-1 ; i++) {
            if (collection[i] <= collection[pivotIndex]) {
                swap (collection, i, store);
                store++;
            }
        }
        swap (collection, store, pivotIndex);
        pivotIndex = store;
        return pivotIndex;
    }   

    private void swap(int[] collection, int x, int y) {
        int temp = collection[x];
        collection[x] = collection[y];
        collection[y] = temp;
    } 

    private int selectPivot(int first, int last) {
        return (first+last)/2;
    } 

} 
Sample Code (GitHub)

The details of the Quick Sort class can be viewed here.

The details of the Quick Sort JUnit Test class can be viewed here.

Conclusion

快速排序算法构成较大的一组排序算法的一部分。 通过经验学习是我创建这篇关于Java快速排序算法实现的文章的原因。 我学到了很多关于其他人如何解决其他语言(包括Java中的不同实现)的快速排序算法的知识。

The post Quick Sort Algorithm in Java appeared first on Code2Bits.

from: https://dev.to//code2bits/quick-sort-algorithm-in-java-2c7j

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值