0
我試圖用算法練習,我試圖寫一個prorgam,它使用插入排序算法按升序排列數組中的數字,數組中的數字通過用戶輸入接收。插入排序C++
現在,當我輸入一串隨機數時,它只會按照我放入的順序返回它們,任何人都會發現我的錯誤?見下面的代碼。
#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;'必然是你想要的。 – WhozCraig 2014-10-02 18:57:29
你確定嗎?我剛剛嘗試過你的代碼,它能正常工作。 – 2014-10-02 18:57:29
它真的適合你嗎?我試着創建一個新項目,再次複製並粘貼代碼並構建+運行。但它仍然只以我輸入的順序返回數字。我使用Xcode btw – Birgir 2014-10-02 19:02:36