一个函数,它将显示使用插入排序对 c++ 进行排序的数组的内容

A function which will display the contents of an array being sorted c++ using insertion sort

本文关键字:c++ 插入排序 排序 数组 一个 函数 显示      更新时间:2023-10-16

我有错误,在本节中突出显示"cout <<array[i] <<endl;"。该行在数组[i]下。错误是"类模板"std::array"的参数列表丢失"。我需要一个函数来显示数组的内容,使用插入排序。如果此代码不正确,是否有人知道使用线性搜索输出数组内容的代码。

#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;
    }
}

你没有在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;}
}