-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertionSort.c
More file actions
49 lines (41 loc) · 885 Bytes
/
Copy pathinsertionSort.c
File metadata and controls
49 lines (41 loc) · 885 Bytes
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
41
42
43
44
45
46
47
48
49
// Insertion Sort (decrease and conquer)
/* Time complexity:
best case: Ω(n)
average case: θ(n^2)
worst case: O(n^2)
*/
#include<stdio.h>
#include <stdlib.h>
void display(int arr[], int n)
{
int i;
for(i = 1; i <= n; i++)
printf("%d\t", arr[i]);
}
void insertionsort(int a[], int n)
{
int i, j, temp;
for(i = 2; i <= n; i++)
{
temp = a[i];
j = i - 1;
while(j >= 1 && a[j] > temp)
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = temp;
}
}
void main(){
int i, n, a[20];
printf("enter the no. of elements:\n");
scanf("%d", &n);
for(i = 1; i <= n; i++)
a[i] = rand() % 500 + 1;
printf("random generated array elements:\n");
display(a, n);
insertionsort(a, n);
printf("\nsorted array elements\n");
display(a, n);
}