数组的排序

/** 
 * The method for sorting the numbers 
 */
public class SelectionSortAndInsertionort {
    public static void main(String[] args) {
        double[] list = {1,2,3,4,5,0};
        selectionSort(list);
        for(double l : list){
            System.out.print(l + " ");
        }
        System.out.println("--------------");
        double[] list1 = {1,2,4,5,0};
        insertionSort(list1);
        for(double l : list1){
            System.out.print(l + " ");
        }
    }
    
    //选择排序法
    public static void selectionSort(double[] list){
        for(int i = 0;i < list.length;i++){
            //Find the minimum int the list[i ... list.length]
            double currentMin = list[i];
            int currentMinIndex = i;
            
            for(int j = i;j < list.length;j++){
                if(currentMin > list[j]){
                    currentMin = list[j];
                    currentMinIndex = j;
                }
                
                //Swap list[i] with list[currentMinIndex] if necessary;
                 if(currentMinIndex != i){
                    list[currentMinIndex] = list[i];
                    list[i] = currentMin;
                }
            }
        }
    }
    
    //插入排序法
    public static void insertionSort(double[] list){
        /**insert list[i] into a sorted sublist list[0 ... i-1] 
        so that list[0..i] is sorted.
        */
        for(int i = 0; i < list.length;i++){
            double currentElement = list[i];
            int k;
            for(k = i - 1;k >= 0 && list[k] > currentElement;k--){
                list[k + 1] = list[k];
            }
            
            //Insert the current element into list[k+1]
            list[k + 1] = currentElement;
        }
      }
}

 

posted @ 2017-03-25 10:36  Gsk.Space  阅读(146)  评论(0)    收藏  举报