[英]Could someone please explain why my program isn't sorting the values properly?
For my assignment, we have to build .h file that links the sort.cpp file and the testsort.cpp file.对于我的作业,我们必须构建链接 sort.cpp 文件和 testsort.cpp 文件的 .h 文件。 However when I compile and run the testsort.cpp program it doesnt provide the sorted array.
但是,当我编译并运行 testsort.cpp 程序时,它不提供已排序的数组。 Rather it just outputs the original array.
相反,它只是输出原始数组。 I tired to add a return function to the sort.cpp file but i get the following error:
我厌倦了向 sort.cpp 文件添加返回函数,但出现以下错误:
error: return-statement with a value, in function returning 'void' [-fpermissive] return A;错误:带有值的返回语句,在返回“void”的函数中 [-fpermissive] 返回 A;
testsort.cpp测试排序文件
#include <iostream>
#include <cstdlib>
#include "sort.h"
int main()
{
const int n = 10;
int i, isort;
float A[n];
for (i=0;i<n;i++)
{
A[i] = float(rand())/RAND_MAX;
}
for (i=0;i<n;i++)
{
std::cout << A[i] << " ";
}
std::cout << " unsorted\n";
std::cout << "Enter 1 for insertion sort, 2 for partition test, 3 for quick sort\n";
std::cin >> isort;
switch (isort)
{
case 1:
InsertionSort( A, n );
break;
case 2:
// std::cout << "Count for small sub-array " << Partition( A, n ) << "\n";
break;
case 3:
// QuickSort(A,n);
break;
default:
std::cout << isort << " is not an allowed choice\n";
}
for (i=0;i<n;i++)
{
std::cout << A[i] << " ";
}
std::cout << " sorted\n";
}
Sort.h排序.h
#ifndef SORT_H
#define SORT_H
void InsertionSort (float A[], int n){}
#endif
Sort.cpp排序文件
#include <iostream>
#include <cmath>
#include "sort.h"
void InsertionSort (float A[], float n)
{
int value;
int j;
for (int i = 1; i < n; i++)
{
value = A[i];
j = i;
while(j > 0 && A[j-1] > value)
{
A[j] = A[j-1];
j--;
}
A[j] = value;
}
//return A;
//std::cout<<"Running Insertion Sort\n";
}
The way you are using sort.h and sort.cpp is wrong.您使用 sort.h 和 sort.cpp 的方式是错误的。 Your insertion sort function in sort.cpp is never being called.
sort.cpp 中的插入排序函数永远不会被调用。 What I tried was that I replaced your blank insertion sort function in sort.h with the function written in sort.cpp.
我尝试的是将 sort.h 中的空白插入排序函数替换为 sort.cpp 中编写的函数。 And deleted sort.cpp file.
并删除了 sort.cpp 文件。 Also you need to change the datatype of value in your insertion sort function to float as you are using a float array.
您还需要在插入排序函数中将值的数据类型更改为 float,因为您正在使用 float 数组。 These two changes and your sorting function is working fine.
这两个更改和您的排序功能工作正常。
Sort.H排序.H
#ifndef SORT_H
#define SORT_H
void InsertionSort (float A[], float n)
{
float value;
int j;
for (int i = 1; i < n; i++)
{
value = A[i];
j = i;
while(j > 0 && A[j-1] > value)
{
A[j] = A[j-1];
j--;
}
A[j] = value;
}
//return A;
//std::cout<<"Running Insertion Sort\n";
}
#endif
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.