Write a code using the insertion sort technique to sort numbers using descending orders.
Sample Input:
Enter total input: 5
Enter the numbers: 4 5 8 9 10
Sample Output:
Descending orders are: 10, 9, 8, 5, 4.
Soultion:
#include <math.h>
#include <stdio.h>
void insertionSort(int arr[], int n)
{
int i, key, 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;
}
}
void printArray(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main()
{
int n,x;
printf("total input: ");
scanf("%d",&n);
int arr[n+1];
for(int i=0;i<n;i++){
scanf("%d",&x);
arr[i] = x;
}
insertionSort(arr, n);
printArray(arr, n);
return 0;
}
Output: