快速排序

来源:互联网 发布:沧州管家婆软件总代理 编辑:程序博客网 时间:2024/05/19 02:25

package com.example;//快速排序public class Test {    public static void main(String[] args) {        int[] arr={5,2,8,4,9,1};        sort(arr,0,arr.length-1);        freach(arr);    }    //排序一次    public static int quickSort(int[] arr, int start, int end) {        int key = arr[start];        while (start < end) {            //从右向左            while (end > start && arr[end] > key) {                end--;            }            arr[start] = arr[end];            //从左向右            while (end > start && arr[start] <= key) {                start++;            }            arr[end] = arr[start];        }        arr[end] = key;        return end;    }    public static void sort(int[] arr, int start, int end) {        if (start >= end) {            return;        }        int i = quickSort(arr, start, end);        sort(arr, start, i - 1);        sort(arr, i + 1, end);    }    //遍历数组    public static void freach(int[] arr) {        System.out.print("[");        for (int i = 0; i < arr.length; i++) {            if (i == arr.length - 1) {                System.out.print(arr[i] + "]");            } else {                System.out.print(arr[i] + ", ");            }        }    }}


结果:[1, 2, 4, 5, 8, 9]

0 0
原创粉丝点击