【问题标题】:Insertion sort c++ [closed]插入排序c ++ [关闭]
【发布时间】:2014-10-02 18:50:52
【问题描述】:

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

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

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

【问题讨论】:

  • 我不认为int i = i; 一定是你想要的。
  • 你确定吗?我刚刚试过你的代码,它工作正常。
  • 它真的适合你吗?我尝试创建一个新项目,再次复制并粘贴代码并构建+运行。但它仍然只按照我输入的顺序返回数字。我正在使用 Xcode 顺便说一句
  • 我应该用什么代替 i @WhozCraig
  • int i = i 是未定义的行为,因此如果幸运的话它可以正常工作,但不能保证。

标签: c++ sorting insertion-sort


【解决方案1】:

工作正常,只需更换

int i = i;

与:

int i = 0;

【讨论】:

    【解决方案2】:

    这是你的问题:

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

    应该是这样的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多