Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        5年前关闭。
                                                                                            
                
        
我正在尝试使用算法,并且正在尝试编写一个程序,该程序使用插入排序算法以升序排列数组中的数字,该数组中的数字是通过用户输入接收的。

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

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

最佳答案

这是你的问题:

for (int i = i; i < numberUsed; i++)


应该是这样的:

for (int i = 0; i < numberUsed; i++)

10-02 21:11