C++資料結構與演算法:選擇排序

來源:互聯網
上載者:User

選擇排序也是一種簡單排序。這種排序的演算法是:首先找出最大的元素,把它移動交換到a[n-1],然後在餘下的n-1個元素中選擇最大的元素並把它移動交換到a[n-2],如此迭代下去即可完成排序。代碼如下:

// BubbleSort.cpp : 定義控制台應用程式的進入點。//

 

// SelectionSort.cpp : 定義控制台應用程式的進入點。//#include "stdafx.h"#include <cmath>#include <iostream>using namespace std;#define  MAXNUM 20template<typename T>void Swap(T& a, T& b){    int t = a;    a = b;    b = t;}template<typename T>int Max(T a[], int n){//尋找數組a[0:n-1]中最大元素的位置    int pos = 0;    for(int i =1 ;i < n; i++)    {        if(a[pos] < a[i])            pos = i;    }    return pos;}template<typename T>void SelectSort(T a[],int n){//對數組a[0:n-1]中的n個元素進行選擇排序    for(int size = n;size > 1; size--)    {        int j = Max(a,size);        Swap(a[j],a[size-1]);    }        }int _tmain(int argc, _TCHAR* argv[]){    int a[MAXNUM];    for(int i = 0 ;i< MAXNUM; i++)    {        a[i] = rand()%(MAXNUM*5);    }        for(int i =0; i< MAXNUM; i++)        cout << a[i] << "  ";    cout << endl;    SelectSort(a,MAXNUM);    cout << "After BubbleSort: " << endl;    for(int i =0; i< MAXNUM; i++)        cout << a[i] << "  ";    cin.get();    return 0;}

 

聯繫我們

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