排序算法之快速排序

几种排序算法中,比较快速且不浪费空间的排序算法,就是快速排序。

java实现快速排序的代码:

package yushen0.sort;

/**
 * 
 * @class_name QuickSort.java
 * @package_name yushen0.sort
 */
public class QuickSort {

    public static void main(String[] args) {

        int[] nums = { 20, 56, 34, 28, 69, 77, 2, 5, 89, 100 };
        StringBuilder strBuilder = new StringBuilder();
        strBuilder.append("排序之前:{");
        for (int i : nums) {
            strBuilder.append(i + ",");
        }
        String str = strBuilder.toString().substring(0, strBuilder.toString().length() - 1);
        System.out.println(str + "}");

        quickSort(nums, 0, nums.length - 1);

        strBuilder.setLength(0);
        strBuilder.append("排序之后:{");
        for (int i : nums) {
            strBuilder.append(i + ",");
        }
        String str2 = strBuilder.toString().substring(0, strBuilder.toString().length() - 1);
        System.out.println(str2 + "}");
    }

    private static void quickSort(int[] nums, int left, int right) {
        if (left < right) {
            int i = left, j = right, x = nums[left];
            while (i < j) {
                // 从右往左找,第一个小于x的数
                while (i < j && nums[j] >= x)
                    j--;
                if (i < j)
                    nums[i++] = nums[j];
                // 从左往右找,第一个大于x的数
                while (i < j && nums[i] < x)
                    i++;
                if (i < j)
                    nums[j--] = nums[i];
            }
            nums[i] = x;
            quickSort(nums, 0, i - 1);
            quickSort(nums, i + 1, right);
        }
    }
}

先把代码贴上,回头分析


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值