Сортировка вставкой из книги Кормена

Я работаю над книгой Кормена «Введение в алгоритмы», и я создал следующее из псевдокода. Однако первые два элемента массива не отсортированы. Я не могу обнаружить ошибку (возможно, потому, что уже поздно). Так что мне было интересно, может ли кто-нибудь увидеть с первого взгляда.

#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;
}
5
задан Kara 17 May 2015 в 05:48
поделиться