首頁  >  文章  >  Java  >  詳解Java中選擇排序 (Selection Sort_java)的實例教程

詳解Java中選擇排序 (Selection Sort_java)的實例教程

零下一度
零下一度原創
2017-05-31 09:26:341852瀏覽

這篇文章主要介紹了Java資料結構及演算法實例:選擇排序Selection Sort,本文直接給出實現程式碼,程式碼中包含詳細註解,需要的朋友可以參考下

/** 
 * 选择排序的思想: 
 * 每次从待排序列中找到最小的元素, 
 * 然后将其放到待排的序列的最左边,直到所有元素有序 
 *  
 * 选择排序改进了冒泡排序,将交换次数从O(N^2)减少到O(N) 
 * 不过比较次数还是O(N) 
 */ 
package al; 
public class SelectSort { 
   
  public static void main(String[] args) { 
     
    SelectSort selectSort = new SelectSort(); 
    int[] elements = { 14, 77, 21, 9, 10, 50, 43, 14 }; 
    // sort the array 
    selectSort.sort(elements); 
    // print the sorted array 
    for (int i = 0; i < elements.length; i++) { 
      System.out.print(elements[i]); 
      System.out.print(" "); 
    } 
  } 
   
  /** 
   * @author 
   * @param array 待排数组 
   */ 
  public void sort(int[] array) { 
    // min to save the minimum element for each round 
    int min, tmp; 
     
    for(int i=0; i<array.length; i++) { 
      min = i; 
      // search for the minimum element 
      for(int j=i; j<array.length; j++) { 
        if(array[j] < array[min]) { 
          min = j; 
        }         
      } 
      // swap minimum element 
      tmp = array[i]; 
      array[i] = array[min]; 
      array[min] = tmp;       
    } 
  } 
}

【相關推薦】

1. java資料結構排序演算法(1)樹形選擇排序

#2. java資料結構排序演算法(2)歸併排序

3. java資料結構排序演算法(3)簡單選擇排序

#4. java資料結構排序演算法(4)選擇排序

以上是詳解Java中選擇排序 (Selection Sort_java)的實例教程的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn