// main program
#include <stdio.h>
#include <stdlib.h>
# include “sortingfunctions.h”
# include “helperfunctions.h”
# define ARRAYSIZE 10
int main(int argc, char** argv) {
int i;
// dynamically allocate memory space for an array
int *arrayPtr = (int *) malloc(ARRAYSIZE*sizeof(int));
fillArray(arrayPtr, ARRAYSIZE, 20, 50);
neatPrint(arrayPtr, ARRAYSIZE, 10, 3);
int ct = selectionSort(arrayPtr, ARRAYSIZE);
printf(“n the number of swapping in selection sort is :%dn”,ct);
neatPrint(arrayPtr, ARRAYSIZE, 10, 3);
printf(“n insertion sort n”);
fillArray(arrayPtr, ARRAYSIZE, 20, 50);
neatPrint(arrayPtr, ARRAYSIZE, 10, 3);
int cnt = insertionSort(arrayPtr, ARRAYSIZE);
printf(“n the number of swapping in insertion sort is :%d”,cnt);
neatPrint(arrayPtr, ARRAYSIZE, 10, 3);
return (EXIT_SUCCESS);
}
//sortingfunction.c
# include “sortingfunctions.h”
#include<stdio.h>
int selectionSort(int *const data, int size)
{
int i,j,min,*swap;
int count;
for (i = 0; i < size; i++)
{
min = i;
for ( j = i + 1 ; j < size ; j++ )
{
if ( *(data+min) > *(data+j) )
min = j;
}
if ( min != i )
{
count++;
*swap = *(data+i);
*(data+i) = *(data+min);
*(data+min) = *swap;
}
}
/* for (i = 0; i < size; i++)
{
min = i;
for ( j = i+1; j < size; j++)
{
if (*(data+j) < *(data+i))
min = j;
}
if (min != i) {
int *temp;
count++;
temp = *(data + i);
*(data + i) = *(data + min);
*(data + min) = temp;
}
}
printf(“Got in”);
for (i = 0; i < size; i++)
printf(“t%d”, *(data + i));*/
return count;
}
int insertionSort(int *const data, int size) {
int i = 1;
int j = i;
int t;
int count = 0;
for (i = 1; i < size; ++i) {
for (j = 0; j < size; ++j) {
if ( *(data + i)< *(data + j)) {
count++;
t = *(data + i);
*(data + i) = *(data + j);
*(data+j) = t;
}
}
}
return count;
}
//helperfunctions.c
#include “helperfunctions.h”
#include <stdlib.h>
# include <stdio.h>
void swap(int *num1, int * num2) {
int temp;
temp = *num1;
*num1 = *num2;
*num2 = temp;
}
void fillArray(int * const data, int size, int min, int max) {
int i;
for (i = 0; i < size; i++) {
*(data + i) = rand() % (max – min + 1) + min;
}
}
void neatPrint(int *const data, int size, int numPerLine, int fieldSize) {
int i;
printf(“n”);
for (i = 0; i < size; i++) {
printf(“t%d”, *(data + i));
if (i == numPerLine)
printf(“n”);
}
}
//sortingfunctions.h
#ifndef SORTINGFUNCTIONS_H
#define SORTINGFUNCTIONS_H
int selectionSort(int * const data, int size);
int insertionSort(int * const data, int size);
#endif /* SORTINGFUNCTIONS_H */
//helperfunctions.h
#ifndef HELPERFUNCTIONS_H
#define HELPERFUNCTIONS_H
#ifdef __cplusplus
extern “C” {
#endif
void swap(int *num1, int * num2);
void fillArray(int * const data, int size, int min, int max);
void neatPrint(int *const data, int size, int numPerLine, int fieldSize);
#ifdef __cplusplus
}
#endif
#endif /* HELPERFUNCTIONS_H */
sample output:
