You are on page 1of 2

Insertion sort:

Introduction:-

 Insertion sort works by inserting an element at its suitable place in each iteration.
 The array elements are compared with each other sequentially and then arranged
simultaneously in some particular order.
 It is less efficient on large lists.

Example:-

Complexity:-
Best case: Θ(n)
Worst Case: Θ (n^2)
Average case: Θ(n^2)

Program:-
#include <stdio.h>
#include <time.h>
int main()
{

int n, i, j, v;
int arr[50];
double time_spent= 0.0;
printf("Please Enter number of elements\n");
scanf("%d", &n);
printf("Please Enter %d integers\n", n);
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);

clock_t begin = clock();

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


j = i;
while ( j > 0 && arr[j-1] > arr[j]){
v = arr[j];
arr[j] = arr[j-1];
arr[j-1] = v;
j--;
}
}
printf("Sorted list in ascending order:\n");
for (i = 0; i <= n - 1; i++)
printf("%d\n", arr[i]);

clock_t end= clock();

time_spent += (double)(end-begin)/ CLOCKS_PER_SEC;


printf("Time taken to execute program is %f seconds",time_spent);
return 0;
}

Output:-

You might also like