INSERTION SORT
Implemented using C Language
C Language Code:
INSERTION.C
// INSERTION SORTING using C Language
#include <stdlib.h>
#include <stdio.h>
#include <process.h>
#define NUM_ITEMS 5
void insertionSort(int numbers[], int array_size);
void prnArray(int numbers[], int array_size) ;
int numbers[NUM_ITEMS];
int main()
{
int i;
clrscr() ;
//seed random number generator
srand(getpid());
//fill array with random integers
for (i = 0; i < NUM_ITEMS; i++)
numbers[i] = rand();
printf("\nBefore Insertion Sort\n");
prnArray(numbers, NUM_ITEMS) ;
//perform insertion sort on array
insertionSort(numbers, NUM_ITEMS);
printf("\nAfter Insertion Sort\n");
prnArray(numbers, NUM_ITEMS) ;
}
void insertionSort(int numbers[], int array_size)
{
int i, j, index ;
for (i=1; i < array_size; i++)
{
index = numbers[i];
j = i;
while ((j > 0) && (numbers[j-1] > index))
{
numbers[j] = numbers[j-1];
j = j - 1;
}
numbers[j] = index ;
}
}
void prnArray(int numbers[], int array_size)
{
int x ;
for(x=0; x < array_size; x++)
printf("%d\t", numbers[x]) ;
}
No comments:
Post a Comment