c語言選擇排序

來源:互聯網
上載者:User

標籤:color   快速   數字   替換   排序   過程   簡單   小數   1.5   

  簡單選擇排序是經常用到的一種排序演算法.

  原理: 

 1.簡單選擇排序一句話概括:每次選擇無序數列中最小的將其放在有序數列的最後。

 2.在簡單選擇排序中,我們用初始化的數字int a[6]={2,5,6,3,1,4}

3.演算法基本執行步驟1:找到初始的無序數組中最下的數,將其放在數組的頭部。交換最小數和數組頭部元素即可(這是與冒泡有區別的地方)。

 1 #include <stdio.h> 2 #include <stdlib.h> 3  4 /* 5  * 簡單選擇排序一句話概括:每次選擇無序數列中最小的將其放在有序數列的最後。 6  * 二、在簡單選擇排序中,我們用初始化的數字int a[6]={2,5,6,3,1,4} 7  * 三、演算法基本執行步驟1:找到初始的無序數組中最下的數,將其放在數組的頭部。交換最小數和數組頭部元素即可(這是與冒泡有區別的地方)。 8  */ 9 10 //替換11 void swap(int a[],int i,int j){12     int temp = a[i];13     a[i] = a[j];14     a[j] = temp;15 }16 17 //快速排序18 void select_sort(int a[],int l)19 {20     // l = 621     int i,temp,j,k;22     /*23      * 推導過程 2,5,6,3,1,424      * i = 0 temp = 2 ,k =0 搜尋到最小值1, k = 4 -> 1,5,6,3,2,425      * i = 1 temp = 5 ,k =1搜尋到最小值2, k = 4   ->   1,2,6,3,5,426      * i = 2 temp = 6 ,k =2搜尋到最小值3  k = 3 ->   1,2,3,6,5,427      * i = 3 temp = 6 ,k =3搜尋到最小值4  k = 5 ->   1,2,3,4,5,628      * i = 4 temp = 5 ,k =4搜尋不到   k = 4    k和i相同不做任何操作29      */30 31     //最後一次不用迴圈32     for (i=0;i<l-1;i++){33         //擷取頭元素的值34         temp = a[i];35         k = i;36 37         //printf("%d\n",temp);38         //從第i+1 元素開始尋找,如果找到比首元素小就替換39         for (j = i+1;j<l;j++){40 41             if (a[j] < temp){42                 //先記錄下來最小值43                 temp = a[j];44                 k = j; //最小值的下標45             }46         }47 48         //替換49         if ( i != k )50             swap(a,i,k);51     }52 53 }54 55 void main()56 {57     int a[] = {2,5,6,3,1,4};58     int i,l = sizeof(a) / sizeof(int);59 60     //選擇排序61     select_sort(a,l);62 63     printf("選擇排序後:\n");64     for ( i = 0; i < l; ++i) {65         printf("%d\n",a[i]);66     }67 68 }

 

 

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.