C++ 选择排序(selectionSort)

一、思路

       每次取剩下没排序的数中的最小数,然后,填到对应位置。(可以使用a[0]位置作为暂存单元)

       如下:

       

 

二、实现程序:

#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 << "请输入要排序的数的个数:";
    cin >> n;
    cout << "请输入要排序的数:";
    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; // 保存最小数的位置
        for(j = i; j <= n; j++) { // 找比arr[i]更小的值
            if(arr[j] < arr[pos]) {
                pos = j; // 指向更小的数的位置
            }
        }
        if(pos != i) { // 找到了更小的值,就交换位置
            arr[0] = arr[i]; // arr[0]作为暂存单元
            arr[i] = arr[pos];
            arr[pos] = arr[0];
        }
    } // for
} // SelectSort

测试数据:

7

20 12 50 70 2 8 40

测试结果:

猜你喜欢

转载自blog.csdn.net/chuanzhouxiao/article/details/89006784