【发布时间】:2021-03-04 11:11:06
【问题描述】:
对于我的任务,我们必须构建链接 sort.cpp 文件和 testsort.cpp 文件的 .h 文件。但是,当我编译并运行 testsort.cpp 程序时,它不提供排序数组。相反,它只是输出原始数组。我厌倦了向 sort.cpp 文件添加返回函数,但出现以下错误:
错误:带有值的返回语句,在函数中返回 'void' [-fpermissive] 返回一个;
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";
}
排序.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";
}
【问题讨论】:
-
为什么
InsertionSort的n参数类型为float而不是size_t? -
您应该对所有数组索引器使用
size_t而不是int:stackoverflow.com/questions/3340880/… -
您的排序算法错误。回去研究一下插入排序算法。