2016-12-13 88 views
0

我的插入排序將每個數字排序,但第一個數字。它從第二個元素到最後一個元素進行排序,但它從不包含第一個元素。我的插入排序有什麼問題。我將此代碼基於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 

收到我的僞如果有複製權的問題,我將取消僞代碼。

正如你所看到的,我的第一個元素沒有排序,並且由於某種原因從未被排序。我的代碼有什麼問題?

+0

'而(I> 0 ...' – user2357112

+0

它應該是在我> = 0 – user1470901

回答

4

更改while循環

while(i >= 0 && data[i] > key) 

下面是更新後的代碼:

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

你?它是正確的,它現在可以工作,但是僞代碼現在被認爲是錯誤的嗎?僞代碼表示狀態(i> 0),我沒有錯誤地輸入它 – user1470901

+1

@ user1470901:僞代碼使用從1開始索引的序列 – user2357112

+0

Ah I看,非常感謝! – user1470901

相關問題