【发布时间】:2012-01-02 14:34:00
【问题描述】:
我正在阅读 Cormen 的“算法简介”一书,并从伪代码创建了以下内容。但是,Array 的前两个元素似乎没有排序。我无法发现错误(可能是因为它迟到了)。所以我想知道是否有人可以第一眼看到。
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int input;
cout << "Enter length of desired array." << "\n";
cin >> input;
cout << "\n";
int A [input];
//Populate and print the Array.
for(int i=0; i<input; i++){
A[i] = rand()%99-1;
cout << A[i] << " ";
}
cout << "\n";
//Insertion sort.
for(int j=2; j<input; j++){ //Iterate through the Array.
int key = A[j]; //Store the current element into key.
int i = j-1; //Iterator for while loop.
while(i>0 && A[i]>key){ //Loop to insert A[j] into the sorted sequence.
A[i+1] = A[i]; //Move the element.
i=i-1; //New value of i.
A[i+1] = key; //Update the key
}
}
for(int i=0; i<input; i++){
cout << A[i] << " ";
}
return 0;
}
【问题讨论】:
-
你试过调试这个吗?您是否在最小数据集上运行?
-
那本书使用基于 1 的索引 iirc,这将是您的问题。
标签: c++ algorithm sorting insertion-sort