无法弄清楚为什么我的打印阵列要替换元素

Can't figure out why my Print Array is replacing elements

本文关键字:阵列 替换 元素 打印 我的 弄清楚 为什么      更新时间:2023-10-16

我正在上C++课,我们已经得到了指针。 我们得到的任务基本上是通过传递指针作为各种函数的参数来对从文本文件中读取的数组进行气泡排序。 我认为我有一个不错的设置来输出我正在寻找的内容,但是对于特定操作,当没有写入数组时,我会得到一个零作为元素。

#include <iostream>
#include <fstream>
using namespace std;
int capacity;
int count;
int readData(int *&arr);
void swap(int *xp, int *yp);
void bsort(int *arr, int last);
void writeToConsole(int *arr, int last);
void bubble_sort(int *arr, int last, int(*ptr)(int, int));
int ascending(int a, int b);
int descending(int a, int b);
int main() {
int *whatever = NULL;
count = readData(whatever);
cout << "Raw array data:" << endl;
writeToConsole(whatever, capacity);
cout << "After simple bubble sort:" << endl;
bubble_sort(whatever, capacity, ascending);
writeToConsole(whatever, capacity);
cout << "Now descending:" << endl;
bubble_sort(whatever, capacity, descending);
writeToConsole(whatever, capacity);

return 0;
}
int readData(int *&arr) {
ifstream inputFile;
inputFile.open("data.txt");
if (!inputFile) {
cout << "Error!";
}
inputFile >> capacity;
arr = new int[capacity];
for(int i = 0; i < capacity; i++){
inputFile >> arr[i];
}
inputFile.close();
return capacity;
}
void swap(int *xp, int *yp) {  
int temp = *xp;  
*xp = *yp;  
*yp = temp;  
}
void bsort(int *arr, int last) {
int i, j; 
bool swapped; 
for (i = 0; i < last + 1; i++) 
{ 
swapped = false; 
for (j = 0; j < last-i; j++) 
{ 
if (arr[j] > arr[j+1]) 
{ 
swap(arr[j], arr[j+1]); 
swapped = true; 
} 
} 
// IF no two elements were swapped by inner loop, then break 
if (swapped == false) 
break; 
} 
} 
void writeToConsole(int *arr, int last) {
cout << "[ ";
for(int i = 0; i < last; i++){
cout << arr[i] << " ";
}
cout << "]" << endl;
}
void bubble_sort(int *arr, int last, int(*ptr)(int, int)){
int i, j; 
bool swapped; 
for (i = 0; i < last; i++) 
{ 
swapped = false; 
for (j = 0; j < last-i; j++) 
{
//Use the function pointer to determine which logic to use
if (ptr(arr[j] , arr[j+1])) 
{ 
swap(arr[j], arr[j+1]); 
swapped = true; 
} 
}  
// IF no two elements were swapped by inner loop, then break 
if (swapped == false) 
break; 
} 
}
int ascending(int a, int b){
return a > b;
}
int descending(int a, int b){
return a < b;
}

我的输出如下所示:

原始数组数据: [ 8 4 7 2 9 5 6 1 3 ] 简单的气泡排序后: [ 0 1 2 3 4 5 6 7 8 ] 现在降序: [ 9 8 7 6 5 4 3 2 1 ]

关于为什么我的第二种是零的任何想法? 谢谢!

你必须在bubble_sort函数中做这个改变

for (j = 1; j < last - i; j++)
{
//Use the function pointer to determine which logic to use
if (ptr(arr[j-1], arr[j]))
{
swap(arr[j-1], arr[j]);
swapped = true;
}
}