演算法(第四版)學習筆記之java實現選擇排序

來源:互聯網
上載者:User

標籤:排序   java   演算法   

選擇排序步驟:

1.找到數組中參與遍曆比較的所有元素中的最小元素的下標;

2.將最小元素與數組中參與遍曆比較的第一個元素進行交換(如果第一個元素就是最小元素的話,那麼也會進行一次交換);

3.若數組中還有需要參與遍曆比較的元素,則跳轉到步驟1;否則排序結束。


在演算法第四版中給出的所有排序均是適用於任意實現了Comparable介面的資料類型,若要將數字作為測試案例,請勿使用基礎資料型別 (Elementary Data Type),改用Integer等實現了Comparable介面的對象。

選擇排序代碼如下:

/** *  * @author seabear * @Description 選擇排序每次遍曆總是返回參與遍曆的元素中最小元素的下標,並將該最小元素與參與遍曆的首元素進行交換 */public class SelectionSort {public static void sort(Comparable[] a){int N = a.length;int minFlag = 0;for(int i = 0; i < N; i++){minFlag = i;for(int j = i + 1; j < N; j++){if(less(a[j],a[minFlag])){minFlag = j;}}exch(a,i,minFlag);}}private static boolean less(Comparable v,Comparable w){return v.compareTo(w) < 0;}private static void exch(Comparable[] a ,int i,int j){Comparable temp = a[i];a[i] = a[j];a[j] = temp;}private static void show(Comparable[] a){for(int i = 0; i < a.length; i++){System.out.print(a[i] + " ");}System.out.println();}private static boolean isSort(Comparable[] a){for(int i = 1 ; i < a.length ; i++){if(less(a[i],a[i-1])){return false;}}return true;}public static void main(String[] args){Integer[] a = new Integer[10];for(int i = 0; i < 10; i++){a[i] = (int) (Math.random() * 10 + 1);System.out.print(a[i] + " ");}System.out.println();sort(a);assert isSort(a);show(a);}}


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

演算法(第四版)學習筆記之java實現選擇排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.