Your second task is to implement the Insertion Sort algorithm by making a function with the following prototype; void insertion_sort(int * ptr_array, int size, int order); This function takes as input a pointer to the start of the array, and the array size and sorts it inplace. The last input to the function is the sorting order (0 for ascending and 1 for descending).
#include <stdio.h>
void insertion_sort(int *ptr_array, int size, int order)
{
int i, j;
for (i=1; i<size; i++) {
int x = ptr_array[i];
for (j=i-1; j>=0; j--) {
if ( order ? ptr_array[j] < x : ptr_array[j] > x) {
ptr_array[j+1] = ptr_array[j];
}
else {
break;
}
}
ptr_array[j+1] = x;
}
}
int main()
{
int A[] = {1, 2, 3, 4, 5};
int n = sizeof(A) / sizeof(A[0]), i;
insertion_sort(A, n, 1);
printf("Descending sort: ");
for (i=0; i<n; i++)
printf("%d ", A[i]);
printf("\n");
insertion_sort(A, n, 0);
printf("Ascending sort: ");
for (i=0; i<n; i++)
printf("%d ", A[i]);
printf("\n");
return 0;
}
Comments
Leave a comment