Java编程思想与读书笔记

快排的2种方法(仅代码演示)

2018-08-24  本文已影响12人  young_dreamer
package com.algorithm.quciksort;

/**
 * Created by young on 2018/8/24.
 */
public class QuickSort {
    public static void main(String[] args) {
        int[] nums = new int[10];
        int[] nums2 = new int[10];

        for (int i = 0; i < 10; i++) {
            nums[i] = (int) (Math.random() * 100);
            nums2[i] = (int) (Math.random() * 100);
        }

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

        for (int i = 0; i < 10; i++) {
            System.out.print(nums[i] + "  ");
        }

        System.out.println();

        for (int i = 0; i < 10; i++) {
            System.out.print(nums2[i] + "  ");
        }
    }

    public static int quickSort(int[] nums, int low, int high) {
        if (low < high) {
            int mid = partition(nums, low, high);
            quickSort(nums, low, mid - 1);
            quickSort(nums, mid + 1, high);
        }

        return low;
    }

    public static int partition(int[] nums, int low, int high) {
        int pivot = nums[low];
        while (low < high) {
            while (low < high && nums[high] >= pivot) high--;
            nums[low] = nums[high];
            while (low < high && nums[low] <= pivot) low++;
            nums[high] = nums[low];
        }
        nums[low] = pivot;
        return low;
    }

    public static int partition2(int[] nums, int low, int high) {
        int start = low;

        for (int i = high; i > low; i--) {
            if (nums[i] >= nums[start]) {
                swap(nums, high--, i);
            }
        }
        swap(nums,start,high);
        return high;
    }

    public static int quickSort2(int[] nums, int low, int high) {
        if (low < high) {
            int mid = partition2(nums, low, high);
            quickSort2(nums, low, mid - 1);
            quickSort2(nums, mid + 1, high);
        }
        return low;
    }


    public static void swap(int[] nums, int a, int b) {
        int tmp = nums[a];
        nums[a] = nums[b];
        nums[b] = tmp;
    }
}

随机运行结果:
8  44  46  48  59  64  75  76  79  81  
4  16  19  35  60  78  78  86  91  96
上一篇 下一篇

猜你喜欢

热点阅读