Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insertion Sort from T Cormen Book

I am working through the "Introduction to Algorithms" book by Cormen, and I have created the following from pseudocode. However, the first two elements of the Array do not seem to be sorted. I cannot spot the error (possibly because its late). So I was wondering if anybody could see from first glance.

#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;
}
like image 635
Jack H Avatar asked Nov 21 '11 00:11

Jack H


2 Answers

I haven't looked too carefully, but I think the book's pseudocode uses one-based indexing, and for coding in C (or most modern languages) you need to adjust it to zero-based indexing.

The principal suspect is

for(int j=2; j<input; j++)

Where you might want to start at 1 instead of 2.

The termination condition

while(i>0 && A[i]>key)

might also need to be changed to ensure you're above -1 rather than 0.

EDIT:

After a bit closer look, I'm pretty sure you do also have to adjust that while.

You should also of course review all upper limits for similar off-by-one issues.

like image 153
Don Roby Avatar answered Sep 25 '22 16:09

Don Roby


change to for (int j = 1; ...)

like image 30
necromancer Avatar answered Sep 23 '22 16:09

necromancer