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

c++1178:成绩排序不用结构体

合适的话 发布于 2022-08-12 13:55, 1579 次点击
7 回复
#2
md000000002022-08-12 14:55
这个需求好奇怪,可以手写排序。
#3
sloth6462022-08-12 15:26
// 假设数据在数组中
void select(int *arr, int len){
    int _index;
    for (int i = 0; i < len - 1; i++){
        _index = i;
        for (int j = i + 1; j < len; j++) {
            if (arr[_index] > arr[j]) {
                _index = j;
            }
        }
        if (i != _index){
            swop(arr + i, arr + _index);// 交换数据
        }
    }
}
#4
宋宇轩2022-08-12 16:45
题目发一下
#5
md000000002022-08-12 16:57
我觉得楼主应该是有两个数组,但不想用结构体把他们串起来然后调用排序指令。这种情况我觉得可以手写排序。
#6
apull2022-08-12 21:13
不用结构体用class呗。
#7
md000000002022-08-12 23:53
这个是原地排序两个数组的代码
程序代码:

#include <string>
#include <algorithm>

using namespace std;

void QuickSort(string name[], float score[], int left, int right) {
    // int pivot = score[right];
    int pivot = score[rand() % (right - left) + left];

    int tmp = left - 1;
    for (int j = left; j < right; j++) {
        if (score[j] < pivot) {
            tmp++;
            swap(score[j], score[tmp]);
            swap(name[j], name[tmp]);
        }
    }
    tmp++;
    swap(score[right], score[tmp]);
    swap(name[right], name[tmp]);
   
    if (left < tmp - 1) QuickSort(name, score, left, tmp - 1);
    if (tmp + 1 < right) QuickSort(name, score, tmp + 1, right);
}


用的时候这样用
string name[] = {"a", "b", "c", "d", "e"};
float score[] = {1, 2, 40, 3, 9};
QuickSort(name, score, 0, 4);


虽然采用了较为稳定版本的快速排序,但这尚不是性能最大化的代码,将就着用,如果数据量过大,你愿意等的话可以用,不愿意等很长时间的话就要另外写代码咯

[此贴子已经被作者于2022-8-13 00:47编辑过]

#8
op1232022-08-14 18:00
还可以直接定义数组来写
1