【问题标题】:Sort an Array of Objects (People) by Last Name C++按姓氏 C++ 对对象(人)数组进行排序
【发布时间】:2017-10-24 04:13:28
【问题描述】:

我正在尝试使用不同的算法按姓氏对对象数组进行排序。

不幸的是,我无法找到一种方法让函数实际对数组进行排序并保存排序后的数组,以便以后打印。

它在排序前后打印出相同的内容。

我将打印对象的样本大小设置为10,这样更易​​于管理,但顺序绝对没有变化,虽然数据文件没有预先排序。

我做错了什么?

代码:

void swap(Person a, Person b){
    Person temp = a;
    a = b;
    b = temp;
}
void bubbleSort(Person a[], const int size){
     for (int i = 0; i < size-1; i++){     
     for (int j = 0; j < size-i-1; j++){
           if (a[j].getLastName() > a[j+1].getLastName())
              swap(a[j], a[j+1]);
       }
    }
}
void selectionSort(Person a[], const int size){
    int minimal_position;
    for (int i=0; i < size-1; i++) {
        minimal_position = i;
        for (int j=i+1; j < size; j++) {
            if (a[j].getLastName() < a[minimal_position].getLastName())
                minimal_position=j;
        }
        if (minimal_position != i){
            swap(a[i], a[minimal_position]);
        }
    }
}
void incertionSort(Person a[], const int size){
    int i, j;
    Person temp;
    for (int i = 1; i < size; i++){
        temp.setPerson(a[i]);
        int j = i-1;
        while (j >= 0 && a[j].getLastName() > temp.getLastName()){
           a[j+1] = a[j];
           j = j-1;
        }
        a[j+1] = temp;
   }
}
void chooseSorting(Person a[], const int size){
    char algorithm;
    cout << "Choose your desired sorting method \n";
    cout << "Type b for bubble sorting, s for selection sorting, ";
    cout << "or i for insertion sorting: \n";
    cout << "Method: ";
    cin >> algorithm;
    cout << endl;
    if(algorithm != 'b' && algorithm != 'i' && algorithm != 's'){
        cout << "Please, choose i, b, or s \n";
        chooseSorting(a, size);
        cout << "Sorted \n";
    }
    else if (algorithm == 'b'){
        bubbleSort(a, size);
        cout << "Sorted \n";
    }
    else if (algorithm == 's'){
        selectionSort(a, size);
        cout << "Sorted \n";
    }
    else {
        incertionSort(a, size);
        cout << "Sorted \n";
    }
}
int main() {
    const int i = chooseDatabase();
    const int size = databaseSize(i);
    const string database_name = chooseDatabaseName(i);
    readFileIntoArray(database_name, arr, size);
    printArray(arr, 10);
    chooseSorting(arr, size);
    printArray(arr, 10);
    return 0;
}

我认为我在传递数组的方式上做错了,但我想不出另一种不会让我的编译器着火的方法 (g++)。

【问题讨论】:

  • 你可以使用std::swap,它确实有效。

标签: c++ arrays sorting object


【解决方案1】:

问题在于交换功能。 您通过值传递对象,您需要通过引用传递它。

void swap(Person &a, Person &b)

这应该可行。

【讨论】:

    【解决方案2】:

    您是否测试过您的 swap() 是否正常工作? 你应该这样写:

    void swap(Person &a, Person &b){
        Person temp = a;
        a = b;
        b = temp;
    }
    

    因为你的代码是在操作人 a 和人 b 的副本,而没有对排序函数中的 a 和 b 做任何努力。

    【讨论】:

      猜你喜欢
      • 2013-11-03
      • 2015-05-25
      • 2020-11-03
      • 1970-01-01
      • 2019-05-06
      • 2015-07-08
      • 1970-01-01
      • 2021-01-04
      • 1970-01-01
      相关资源
      最近更新 更多