I've found this implementation on the web:
void insertSort(int a[], int length) { int i, j, value; int k=0; for(i = 1; i < length; i++) { value = a[i]; for (j = i - 1; j >= 0 && a[j] > value; j--) { a[j + 1] = a[j]; k++; } a[j+1] = value; } printf("k=%d", k); }
I have written this:
#include <stdio.h>
#define SIZE 8
int array1[SIZE] = {77, 33, 44, 11, 88, 22, 66, 55};
void PrintArray()
{
int i = 0;
printf("\n");
for(i=0 ; i<SIZE ; i++)
{
printf("%d, ", array1[i]);
}
}
void Insert(int insertPosition, int insertElementIndex)
{
int temp = array1[insertElementIndex];
int i = 0;
for(i=insertElementIndex ; i>=insertPosition ; i--)
{
array1[i] = array1[i-1];
}
array1[insertPosition] = temp;
}
void InsertionSort()
{
int i = 0;
int j = 0;
int k = 0;
for(i=0 ; i<SIZE ; i++)
{
for(j=0 ; j<=i ; j++)
{
if(array1[i] < array1[j])
{
Insert(j, i);
PrintArray();
}
k++;
}
}
printf("k=%d", k);
}
main()
{
PrintArray();
InsertionSort();
//insertSort(array1, SIZE);
PrintArray();
getch();
}
Is there any problem with this implementation?