【问题标题】:A function which will display the contents of an array being sorted c++ using insertion sort一个函数,它将使用插入排序显示正在排序的 c++ 数组的内容
【发布时间】:2016-06-25 23:37:51
【问题描述】:

我有错误,突出显示“cout

#include <iostream>
#include <string>
#include <sstream>
using namespace std;



int main()
{
    int numbers[SIZE] = { 6,3,1,9,4,12,17,2 };
    for (int i = 0; i < 8; i++)
    {
        cout << array[i] << endl;
    }

    system("pause");
}

const int SIZE = 8;
void insertionSort(int numbers[], int arraySize)
{
    int i, j, insert;

    for (i = 1; i < arraySize; i++)
    {
        insert = numbers[i];
        j = i;
        while ((j > 0) && (numbers[j - 1] > insert))
        {
            numbers[j] = numbers[j - 1];
            j = j - 1;
        }
        numbers[j] = insert;

    }
}

【问题讨论】:

  • 尝试cout &lt;&lt; numbers[i] &lt;&lt; endl;SIZE应该在main之前定义。
  • @knivil 谢谢你的工作
  • 还要注意std::array是标准库中的一个类,通过using namespace std;你已经把它扔到了全局范围内,这使得当你潜在地意味着其他东西时使用标识符array一个错误。
  • @knivil 当我运行程序时数组没有排序,有什么建议吗?

标签: c++ arrays function sorting insertion


【解决方案1】:

你没有在main() 中调用你的函数insertionSort(int numbers[], int arraySize)。因此,原始数组不会发生任何事情。

请注意,您需要在 int main() 中添加 return 0; 语句。并且您需要使用numbers[i] 而不是array[i]。您需要将您的insertionSort() 设置为return“某物”,或者将您的numbers[] 作为参考。另外不要忘记main().之前的函数原型

这应该可行:

const int SIZE = 8;
void insertionSort(int [], int);

int main()
{
    int numbers[SIZE] = { 6,3,1,9,4,12,17,2 };
    insertionSort(numbers, SIZE);
    for (int i = 0; i < 8; i++)
        cout << numbers[i] << endl;

    system("pause");
    return 0;
}

void insertionSort(int MyArray[], int size)
{
    int i, j, insert;

    for (i = 1; i < size; i++){
        insert = MyArray[i];
        j = i;
        while ((j > 0) && (MyArray[j - 1] > insert)){
            MyArray[j] = MyArray[j - 1];
            j = j - 1;}
        MyArray[j] = insert;}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    相关资源
    最近更新 更多