无法弄清楚为什么我的打印阵列要替换元素
Can't figure out why my Print Array is replacing elements
我正在上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;
}
}
相关文章:
- 模板参数替换失败,并且未完成隐式转换
- OpenMP阵列性能较差
- 如何用转义符替换字符串中的所有特殊字符
- 如何将三维尺寸不固定的三维阵列展平为一维阵列
- 当我的阵列太大时出现分段错误
- 为什么除非添加括号,否则构造函数上的模板替换会失败?
- 在一个读写器队列中,我可以用volatile替换原子吗
- 位阵列上的快速AND运算
- 用符号版本替换对函数的所有调用
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- 替换基于地图的所有引用
- 阵列必须使用大括号封闭的初始器进行初始化
- 按平均值替换数组中的元素
- 没有从阵列<float>到阵列<int>的可行转换
- 我可以在这里替换什么,因为我不能在 C# 中使用隐式变量的 lambda 函数?
- 无法弄清楚为什么我的打印阵列要替换元素
- 查找和替换子阵列的最佳方法
- 替换字符阵列C 中的字符
- 用另一个替换多维阵列
- 简单直接替换 2D 阵列