注册 登录
编程论坛 C++教室

用选择法对数组中10个整数从小到大排列

GELUCk 发布于 2018-02-21 18:06, 2013 次点击
书中给出的答案:
#include <iostream>
using namespace std;
int main()
{
    void select_sort(int array[], int n);
    int a[10], i;
    cout << "enter the originl arry:" << endl;
    for (i = 0; i < 10; i++)
        cin >> a[i];
    cout << endl;
    select_sort(a,10);
    cout << "the ssorted array:" << endl;
    for (i = 0; i < 10; i++)
        cout << a[i] << " ";
    cout << endl;
    system("pause");
}
void select_sort(int array[], int n)
{
    int i, j, k, t;

    for (i = 0; i < n - 1; i++)
    {
        k = i;
        for (j = i + 1; j < n; j++)
            if (array[j] < array[k])        
                k = j;
        t = array[k]; array[k] = array[i]; array[i] = t;
    }
}

我自己写的:

#include <iostream>
using namespace std;
void select_sort(int array[], int n);
int main()
{
    void select_sort(int array[], int n);
    int a[10], i;
    cout << "enter the originl arry:" << endl;
    for (i = 0; i < 10; i++)
        cin >> a[i];
    cout << endl;
    select_sort(a, 10);
    cout << "the ssorted array:" << endl;
    for (i = 0; i < 10; i++)
        cout << a[i] << " ";
    cout << endl;
    system("pause");
}
void select_sort(int array[], int n)
{
    int i, j, t;
    for (i = 0; i < n - 1; i++)
    {
        for (j = i + 1; j < n; j++)
            if (array[j] < array[i])
            {
                t = array[j]; array[j] = array[i]; array[i] = t;
                cout << array[i] << " " << array[j] << endl;
            }
    }
}
主要是我的select_sort函数中省去了“k”变量,将这个函数改了一下,这样做有没有问题?
2 回复
#2
moox2018-02-22 00:01
如果是处理10000000个数据,显然是课本的更快点。你的程序把每次比较大的数都进行一次交换位子,当要交换位子的数据多了就会浪费时间在交换上。所以就要一个k来记录比前一个数大的位子,最后只把k位子处的数据进行交换,这样只进行了一次交换,节省了多次交换的时间。
比如 随机生成 0-100000中的10000个数,两个排序的时间为
只有本站会员才能查看附件,请 登录
#3
GELUCk2018-03-04 17:22
哦,原来如此,谢了。
1