選擇排序——C實現

來源:互聯網
上載者:User

標籤:[]   index   輸出   return   序列   void   clu   int   --   

選擇排序:

  選擇排序(Selection sort)是一種簡單直觀的排序演算法。它的工作原理如下。首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然後,再從剩餘未排序元素中繼續尋找最小(大)元素,然後放到已排序序列的末尾。以此類推,直到所有元素均排序完畢。 選擇排序的主要優點與資料移動有關。如果某個元素位於正確的最終位置上,則它不會被移動。選擇排序每次交換一對元素,它們當中至少有一個將被移到其最終位置上,因此對n個元素的表進行排序總共進行至多n-1次交換。在所有的完全依靠交換去移動元素的排序方法中,選擇排序屬於非常好的一種。

C實現:
 1 // 選擇排序 2 #include <stdio.h> 3 int max(int a[], int len); 4  5 int main(void) 6 { 7     int a[] = {6, 23, 2, 54, 12, 6, 8, 100}; 8     int len = sizeof(a)/sizeof(a[0]); 9     int i, t, index;10 11     for (i=len-1; 0<i; i--){12         index = max(a, i+1);13         t = a[index];14         a[index] = a[i];15         a[i] = t;16     }17 18     // 輸出排序後的19     for (i=0; i<len; i++){20         printf("%d ", a[i]);21     }22 23     return 0;24 }25 26 // 找最大的數的下標27 int max(int a[], int len)28 {29     int maxid = 0;30     int i;31     for (i=0; i<len; i++){32         if (a[i] > a[maxid]){33             maxid = i;34         }35     }36     return maxid;37 }

 

選擇排序——C實現

聯繫我們

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