1. 程式人生 > >C++排序(2)——選擇排序

C++排序(2)——選擇排序

#include <iostream>
#include <vector>
using namespace std;

//選擇排序
//演算法時間複雜度 O(n*n)
//額外空間複雜度 O(1)
void Selection_Sort(vector <int> &num_s)
{
    if (num_s.size() == 1)
        return;
    for (int i = num_s.size() - 1; i > 0; i--)
    {
        int Max_temp = 0;
        for (int j =
0; j <= i; j++) { if (num_s[j] > num_s[Max_temp]) Max_temp = j; } int temp = num_s[Max_temp]; num_s[Max_temp] = num_s[i]; num_s[i] = temp; } } int main() { int num; vector <int> num_s; while(cin >>
num) num_s.push_back(num); Selection_Sort(num_s); cout << "the original data is: " << endl; for (int i = 0; i < num_s.size(); i++) cout << num_s[i] << ' '; cout << endl << "the Selection_Sort data is: " << endl;
for(int i = 0; i < num_s.size(); i++) cout << num_s[i] << ' '; system("pause"); return 0; }