Java排序之直接选择排序

一、基本概念

首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,直接选择排序然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。

 

 

二、算法特点

是否稳定:  false

平均时间复杂度:O(n^2)

最差时间复杂度:O(n^2)

最优时间复杂度:O(n^2)

 

 

三、相关代码

public static void main(String[] args) {
        int[] a = { 2, 5, 5, 3, 9, 6, 1, 4, 8, 7 };
        select_sort(a);
        print_array(a);

}

    public static void select_sort(int[] a) {

        for (int i = 0; i < a.length; i++) {
            for (int j = i + 1; j < a.length; j++) {
                if (a[i] > a[j]) {
                    swap(a, i, j);
                }
            }
        }
}

    public static void swap(int[] a, int b, int c) {
        if (b == c)
            return;
        a[b] = a[b] ^ a[c];
        a[c] = a[b] ^ a[c];
        a[b] = a[b] ^ a[c];
    }

    public static void print_array(int[] a) {
        if (a.length == 0)
            return;

        for (int i : a) {
            System.out.print(i + " ");
        }
}

运行结果:

1 2 3 4 5 5 6 7 8 9 
posted @ 2012-10-17 22:26  一瓶珍情  阅读(4224)  评论(0)    收藏  举报