C Program for Insertion Sort On Random Array (Ascending Order)

Problem: Sort a random array of n integers (accept the value of n from user) in ascending order by using insertion sort algorithm.

C program to sort a random array in ascending order using insertion sort

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

#include 
#include 

// Function to display array

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

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

// Function to generate random array

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

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


}


// Function for insertion sort

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

 int Rvalue,i,j;

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

 Rvalue=arr[i];

 j=i-1;

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

 arr[j+1]=Rvalue;

 }
}

// main() function to test the insertion sort
 
void 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");

}

/* Output of above code:-

 Enter the size of array:- 5

 The random array:  83 86 77 15 93

 The sorted array:  15 77 83 86 93

*/