排序演算法之選擇排序

來源:互聯網
上載者:User

標籤:資料結構與演算法   排序演算法   

1.演算法基本思想

            選擇排序方法的基本思想是:第i趟排序是從線性表後面的n-i+1個資料元素中選擇一個值最小的資料元素,並將其與它n-i+1個資料元素中的第1個資料元素交換位置.經過這樣的n-1趟排序以後,初始的線性表成為了一個按值從小到大排列的線性表。

2.流程圖

      流程圖如下所示:


3.演算法實現

public class SelectSort {private static void selectSort(int[]array){int index,temp;for(int i=0;i<array.length-1;++i){index=i;//find the minimum element from the (n-i+1) elementsfor(int j=i+1;j<array.length;++j){if(array[j]<array[index]){index=j;}}if(index!=i){temp=array[index];array[index]=array[i];array[i]=temp;}}}public static void main(String[]args){int[]a=new int[20];for(int i=0;i<20;++i){a[i]=new Random().nextInt(100);}System.out.println("before sort,array is as below:");PrintUtils.print(a);        selectSort(a);        System.out.println("\nafter sort,array is as below:");        PrintUtils.print(a);}}

輸出結果如下:

before sort,array is as below:13 3 43 64 63 82 25 46 13 27 14 49 77 49 58 93 64 33 68 78 after sort,array is as below:3 13 13 14 25 27 33 43 46 49 49 58 63 64 64 68 77 78 82 93 




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

排序演算法之選擇排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.