C++實現選擇排序


選擇排序是蠻力法在排序算法中的一個重要運用,選擇排序開始的時候,我們掃描整個列表,找到它的最小元素然后和第一個元素交換,將最小元素放到它在有序表的最終位置上。然后我們從第二個元素開始掃描列表,找到最后n-1個元素的最小元素,再和第二個元素交換位置,把第二小的元素放在它最終的位置上。如此循環下去,在n-1遍以后,列表就排好序了。

下面給出算法的偽代碼:

SelectSort(A[0...n-1])

for i<-0 to n-2 do

min <- i

for j<- i+1 to n-11 do 

if A[j]<A[min]

min <- j

swap A[j] and A[min]

 

用C++實現如下:

#include <iostream>
//選擇排序
//Shoval
using namespace std;

void SelectSort(auto a[],int n)
{
for(int i=0;i<n-1;i++)
{
int min=i;
for (int j=i;j<n;j++)
{
if(a[j]<a[min])
min=j;
}
swap(a[i],a[min]);
}
}
int main(int argc, char** argv) {
int a[10]={4,5,7,1,8,2,9,0,3,6};
char b[8]="sfvcr";
cout<<"排序前的數組是:"<<endl;
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
for(int i=0;i<5;i++)
cout<<b[i]<<" ";
cout<<endl;
cout<<endl;
cout<<"排序后的數組是:" <<endl;
SelectSort(b,5);
SelectSort(a,10);
for(int i=0;i<10;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
for(int i=0;i<8;i++)
cout<<b[i]<<" ";
return 0;
}

運行結果是:

可見,排序中數組參數的數據類型的auto使該程序可以對字母進行排序。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM