1. 程式人生 > >8種經典演算法之選擇排序

8種經典演算法之選擇排序

選擇排序是一種簡單直觀的排序方法。
排序原理:
第一輪掃描找到最小的數放在最前面;
第二輪掃描找到第二小的數放在第二位;
依次類推。
使得整個序列為有序序列。

選擇排序圖解:
這裡寫圖片描述

程式碼實現:

#include <iostream>
using namespace std;


//選擇排序
void select_sort(int a[] , int len)
{
    //總共比較n-1輪
    for (int i = 0; i < len - 1; i++) {
        //每輪比較n-i次
for (int j = i + 1 ; j < len - i ; j++) { if ( a[i] > a[j] ) { int temp; temp = a[i]; a[i] = a[j]; a[j] = temp; } } } } void print_sort(int a[] , int len) { //輸出整個陣列 for (int i = 0
; i < len; i++) { std::cout<<a[i]<<" "; } } int main(int argc, const char * argv[]) { int a[] = {5 , 1 , 2 , 6 , 4 , 3 , 7 , 9 , 8 ,10}; std::cout<<"您要排序的數為:"<<std::endl; for (int i = 0; i < 10; i++) { std::cout<<a[i]<<" "; } std
::cout<<std::endl; std::cout<<"選擇排序"<<std::endl; select_sort(a, 10); print_sort(a, 10); return 0; }

結果例項:

您要排序的數為:
5 1 2 6 4 3 7 9 8 10
選擇排序
1 2 3 4 5 6 7 9 8 10

大家有問題可以提出來,一起共同學習交流,共同進步。