gpt4 book ai didi

c++ - 插入排序 C++

转载 作者:太空宇宙 更新时间:2023-11-04 16:12:59 24 4
gpt4 key购买 nike

<分区>

我正在尝试使用算法进行练习,我正在尝试编写一个程序,它使用插入排序算法按升序排列数组中的数字,数组中的数字是通过用户输入接收的。

现在当我输入一堆随机数时,它只会按照我输入的顺序返回它们,有人发现我的错误吗?请参阅下面的代码。

#include <iostream>

using namespace std;

const int MAX_SIZE = 20; //global constant

void fillArray(int a[], int size, int& numberUsed)
{
int next = 0;
int index = 0;

cin >> next;

while ((next >= 0) && (index < size)) //Á meðan tala er stærri en 0, og heildarfjöldi minni en 20
{
a[index] = next; //gildi sett inn í array
index++;
cin >> next; //næsta tala lesin inn
}
numberUsed = index; //
}

void sort(int a[], int numberUsed)
{
int j, temp;

for (int i = i; i < numberUsed; i++)
{
temp = a[i];

j = i -1;

while (temp < a[j] && j >= 0)
{
a[j+1] = a[j];
--j;
}
a[j+1] = temp;

}
}

void displayArray(const int a[], int numberUsed)
{
for (int index = 0; index < numberUsed; index++)
cout << a[index] << " ";
cout << endl;
}

int main()
{
cout << "This program sorts numbers from lowest to highest.\n";
cout << "Enter up to 20 nonnegative whole numbers.\n";
cout << "Mark the end of the list with a negative number.\n";

int sampleArray[MAX_SIZE], numberUsed;

fillArray(sampleArray, MAX_SIZE, numberUsed);
sort(sampleArray, numberUsed);

cout << "In sorted order the numbers are:\n";
displayArray(sampleArray, numberUsed);

return 0;
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com