我的插入排序將每個數字排序,但第一個數字。它從第二個元素到最後一個元素進行排序,但它從不包含第一個元素。我的插入排序有什麼問題。我將此代碼基於CLRS本書的僞代碼,我無法調試它出現的問題。爲什麼我的插入排序沒有得到第一個元素?
#include <iostream>
void InsertSort(int data[], int length)
{
//std::cout<<length<<std::endl;
for(int j = 1; j < length; j++)
{
int key = data[j];
int i = j - 1;
while(i > 0 && data[i] > key)
{
data[i + 1] = data[i];
i--;
}
data[i+1] = key;
}
for(int x = 0; x < length; x++)
{
std::cout<<data[x]<<" ";
}
std::cout<<std::endl;
}
int main(int argc, const char * argv[])
{
// insert code here...
//std::cout << "Hello, World!\n";
int foo [] = { 18, 2, 77, 0, 12071 , 21, 45, 98, 54, 80};
InsertSort(foo, 10);
return 0;
}
這裏是我的輸出:18 0 2 21 45 54 77 80 98 12071
這裏是一本書
for j = 2 to A.length
key - A[j]
//Insert A[j] into the sorted sequence A[1.. j - 1]
i = j -1
while i > 0 and A[i] > key
A[i+1] = A[i]
i = i -1
A[i+1] = key
收到我的僞如果有複製權的問題,我將取消僞代碼。
正如你所看到的,我的第一個元素沒有排序,並且由於某種原因從未被排序。我的代碼有什麼問題?
'而(I> 0 ...' – user2357112
它應該是在我> = 0 – user1470901