快速排序的JAVA实现

来源:互联网 发布:阿里云虚拟主机ip地址 编辑:程序博客网 时间:2024/06/16 01:58

总是会模糊这些排序,记录一下快速排序,这是原文链接。https://www.cnblogs.com/zengzhihua/p/4456737.html

算法描述:对于一组给定的记录,通过一趟排序后,将原序列分为两部分,其中前一部分的所有记录均比后一部分的所有记录小,然后再依次对前后两部分的记录进行快速排序,递归该过程,直到序列中的所有记录均有序为止。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package sorting;
 
/**
 * 快速排序
 * 平均O(nlogn),最好O(nlogn),最坏O(n^2);空间复杂度O(nlogn);不稳定;较复杂
 * @author zeng
 *
 */
public class QuickSort {
 
    public static void sort(int[] a, int low, int high) {
        if(low>=high)
            return;
        int i = low;
        int j = high;
        int key = a[i];
        while (i < j) {
            while (i < j && a[j] >= key)
                j--;
            a[i++] = a[j];
            while (i < j && a[i] <= key)
                i++;
            a[j--] = a[i];
        }
        a[i] = key;
        sort(a,low,i-1);
        sort(a,i+1,high);
    }
 
    public static void quickSort(int[] a) {
        sort(a, 0, a.length-1);
        for(int i:a)
            System.out.print(i+" ");
    }
 
    public static void main(String[] args) {
        int[] a = { 49, 38, 65, 97, 76, 13, 27, 50 };
        quickSort(a);
    }
}

  

原创粉丝点击