C Program For Insertion Sort On Random Array (Descending Order)

Problem: Sort a random array in descending order using insertion sort.

Que. What modification is required to insertion sort to sort the integers in descending order?
Answer: We just have check whether the integer before key is less than key or not. If it is, we have to swap it.

C program for insertion sort on random array in descending order

/* Aim: C Program to sort a random array in descending order using insertion sort */

#include<stdio.h>
#include<stdlib.h>

void DisplayArray(int arr[],int n)
{
 int i;

 for(i=0;i<n;i++)
 printf(" %d ",arr[i]);
}

void Generate(int *arr, int n)
{
 int i;

 for(i=0;i<n;i++)
 arr[i]=rand()%100;


}

void InsertionSort(int arr[], int n)
{

 int Key,i,j;

 for(i=1;i<n;i++)
 {

 Key=arr[i];

 j=i-1;

 
 while( j>=0 && arr[j]<key)
 {
  arr[j+1]=arr[j];
  j=j-1;
 }

 arr[j+1]=Key;

 }
}
 
int main()
{
 int arr[100],n;

 printf("\n Enter the size of array:- ");
 scanf("%d",&n);

 Generate(arr,n); // Generating a random array
 
 printf("\n The random array: ");
 DisplayArray(arr,n); // Displaying the array

 InsertionSort(arr,n); // Sorting the array

 printf("\n The sorted array: ");
 DisplayArray(arr,n); // Displaying the sorted array

 printf("\n");

        return 0;
}

Output:

 Enter the size of array:- 5                                                                                                 
                                                                                                                             
 The random array:  83  86  77  15  93                                                                                       
 The sorted array:  93  86  83  77  15