-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsertionsort.c
40 lines (32 loc) · 869 Bytes
/
insertionsort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <stdio.h>
int main()
{
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n], i;
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("Unsorted array: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
for (int i = 1; i < n; i++)
{
int temp = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > temp)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
printf("\nSorted array: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
/*For the best case scenerio (if the list is in assending), the time complexity = O(n).
For the worst case scenerio (if the list is in dessending), the time complexity = O(n2).*/