Answer to Question #196834 in C for Hassam

Question #196834

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).


1
Expert's answer
2021-05-23T14:36:24-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS