SelectionSort

Selection sort is a sorting algorithm. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and it has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.

<Introduction to algorithm>

Consider sorting n numbers stored in array A by first finding the smallest element
of A and exchanging it with the element in AOE1. Then find the second smallest
element of A, and exchange it with AOE2. Continue in this manner for the first n1
elements of A. Write pseudocode for this algorithm, which is known as selection
sort. What loop invariant does this algorithm maintain? Why does it need to run
for only the first n  1 elements, rather than for all n elements? Give the best-case
and worst-case running times of selection sort in ‚-notation.

/*
 * Best  Average  Worst  Memory  Stable
 *  n^2    n^2     n^2      1      No(5,8,5,1,9)
*/
public class SelectionSort {

    public static void sort(int[] a){
        for(int i=0;i<a.length-1;i++){
            int key=a[i];
            int index=i;
            for(int j=i+1;j<a.length;j++){
                if(a[j]<key){
                    key=a[j];
                    index=j;
                }
            }
            a[index]=a[i];
            a[i]=key;
        }
    }
    
    public static void printArray(int[] a){
        for(int i = 0;i < a.length;i++){
            System.out.print(a[i]+" ");
        }
    }
    
    public static void main(String[] args) {
         int[] a={ 2, 0 ,1,5,5, 4, 9, 8, 6, 7, 10, 3 }; 
         sort(a);
         printArray(a);
    }

}

 

posted on 2013-03-28 23:03  melotang  阅读(311)  评论(0)    收藏  举报