按姓氏C ++排序对象数组(人物)

时间:2017-10-24 04:13:29

标签: c++ arrays sorting object

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

不幸的是,我找不到一种方法来使函数实际排序数组并保存已排序的数组,以便以后可以打印。

它在排序之前和之后打印出相同的东西。

我将打印对象的样本大小设置为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 ++)。

2 个答案:

答案 0 :(得分:1)

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

void swap(Person &a, Person &b)

这应该有用。

答案 1 :(得分:1)

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

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

由于您的代码正在运行Person a和Person b的副本,并且在sort函数中没有使用a和b。

相关问题