C++實現(xiàn)選擇排序(selectionSort)
更新時間:2020年04月26日 17:24:47 作者:ChanJose
這篇文章主要為大家詳細介紹了C++實現(xiàn)選擇排序,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了C++實現(xiàn)選擇排序的具體代碼,供大家參考,具體內(nèi)容如下
一、思路
每次取剩下沒排序的數(shù)中的最小數(shù),然后,填到對應(yīng)位置。(可以使用a[0]位置作為暫存單元)
如下:
二、實現(xiàn)程序
#include <iostream> using namespace std; const int maxSize = 100; template<class T> void SelectSort(T arr[], int n); // 選擇排序 int main(int argc, const char * argv[]) { int i, n, arr[maxSize]; cout << "請輸入要排序的數(shù)的個數(shù):"; cin >> n; cout << "請輸入要排序的數(shù):"; for(i = 1; i <= n; i++) // arr[0]不存放值,用來做暫存單元 cin >> arr[i]; cout << "排序前:" << endl; for(i = 1; i <= n; i++) cout << arr[i] << " "; cout << endl; SelectSort(arr, n); cout << "排序后:" << endl; for(i = 1; i <= n; i++) cout << arr[i] << " "; cout << endl; return 0; } // 直接選擇排序 template <class T> void SelectSort(T arr[], int n) { int i, j, pos; for(i = 1; i < n; i++) { // 共作n-1趟選擇排序 pos = i; // 保存最小數(shù)的位置 for(j = i; j <= n; j++) { // 找比arr[i]更小的值 if(arr[j] < arr[pos]) { pos = j; // 指向更小的數(shù)的位置 } } if(pos != i) { // 找到了更小的值,就交換位置 arr[0] = arr[i]; // arr[0]作為暫存單元 arr[i] = arr[pos]; arr[pos] = arr[0]; } } // for } // SelectSort
測試數(shù)據(jù):
7
20 12 50 70 2 8 40
測試結(jié)果:
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
c語言for、while和do-while循環(huán)之間的區(qū)別
大家好,本篇文章主要講的是c語言for、while和do-while循環(huán)之間的區(qū)別,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下2022-01-01字典樹的基本知識及使用C語言的相關(guān)實現(xiàn)
這篇文章主要介紹了字典樹的基本知識及使用C語言的相關(guān)實現(xiàn),這也是ACM等計算機考試和競賽題目的基本知識,需要的朋友可以參考下2015-08-08C語言strlen,strcpy,strcmp,strcat,strstr字符串操作函數(shù)實現(xiàn)
這篇文章主要介紹了C語言strlen,strcpy,strcmp,strcat,strstr字符串操作函數(shù)實現(xiàn),,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下2022-09-09