选择排序

package foo;

import java.util.Arrays;

public class Main {
    
    public static void selectionSort(int[] a, int len) {
        int in, out, min;
        for (out=0;out<len-1;++out) {
            min = out;
            for (in=out+1;in<len;++in) {
                if(a[in]<a[min]) {
                    min = in;
                }
            }
            swap(a, out, min);
        }
    }
    
    public static void swap(int[] a, int index1, int index2) {
        int temp = a[index1];
        a[index1] = a[index2];
        a[index2] = temp;
    }
    
    public static void main(String[] args) throws Exception {
        int[] a = new int[]{3,2,1,5,4};
        selectionSort(a, a.length);
        System.out.println(Arrays.toString(a));
    }
}

选择排序的效率:O(N*N),比较N*N/2,交换<N; 选择排序与冒泡排序比较,比较次数没有明显改变,但交换次数明显减少了很多

posted @ 2014-06-17 17:54  rldts  阅读(159)  评论(0编辑  收藏  举报