C program to sort an array using insertion sort algorithm
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
void insertionSort(int [],int );
int main()
{
int *arr;
int n,i;
printf("\nEnter the no. of elements:\n");
scanf("%d",&n);
arr=malloc(n*sizeof(int));
printf("\nEnter the of elements:\n");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
insertionSort(arr,n);
printf("Sorted array:\n");
for(i=0;i<n;i++)
{
printf("%d\t",arr[i]);
}
return 0;
}
void insertionSort(int arr[],int n)
{
int i, key, j,k;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i-1;
/* Move elements of arr[] that are
greater than key to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}
#include <stdlib.h>
void insertionSort(int [],int );
int main()
{
int *arr;
int n,i;
printf("\nEnter the no. of elements:\n");
scanf("%d",&n);
arr=malloc(n*sizeof(int));
printf("\nEnter the of elements:\n");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
insertionSort(arr,n);
printf("Sorted array:\n");
for(i=0;i<n;i++)
{
printf("%d\t",arr[i]);
}
return 0;
}
void insertionSort(int arr[],int n)
{
int i, key, j,k;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i-1;
/* Move elements of arr[] that are
greater than key to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}
OUTPUT:
Enter the no. of elements:
5
Enter the of elements:
50 20 40 10 30
Sorted array:
10 20 30 40 50