【发布时间】: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,它确实有效。