My implementation of insertion sort seems to be working with the exception of sorting the very first element. I have a small test case here. Can anyone tell me what is wrong with my algorithm?
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
void Insert(int *S, int k)
{
int key = S[k];
int j = k-1;
while(j>0 && S[j] > key)
{
S[j+1] = S[j];
j--;
}
S[j+1] = key;
}
void Insertionsort(int S[], int n)
{
if(n>1)
Insertionsort(S,n-1);
Insert(S,n);
}
int main()
{
srand ( time(NULL) );
int S1_8[8];
for(int i=0; i<8; i++)
S1_8[i] = rand()%100;
Insertionsort(S1_8,8);
for(int i=0; i<8; i++)
{
cout << S1_8[i] << endl;
}
return 0;
}
The first time
Insertis called, it is passedint key = S[8];S[8]is not within array bounds.Make that
Also, in your while condition, it must be
Link to Code