-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertion sort.c
More file actions
48 lines (37 loc) · 986 Bytes
/
insertion sort.c
File metadata and controls
48 lines (37 loc) · 986 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
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int *insertionsort(arr, n);
int main() {
int arr [] = {4, 6, 2, 9, 1, 8, 3, 7, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int st = 0;
int ed = n - 1;
printf("Original Array : ");
for (int i = 0; i <= ed; i ++){
printf("%d ", arr[i]);
}
int *ans = insertionsort(arr, n);
printf("\n--------------\n");
printf("Sorted Array : ");
for (int i = 0; i <= ed; i ++){
printf("%d ", ans[i]);
}
printf("\n--------------\n");
}
int *insertionsort(int arr[], int n){
int *ans, temp;
ans = malloc(sizeof(int) * n);
ans[0] = arr[0];
for (int i = 1; i < n; i ++){
ans[i] = arr[i];
int j = i;
while ((j > 0) & ( ans[j - 1] > ans[j])){
temp = ans[j];
ans[j] = ans[j - 1];
ans[j - 1] = temp;
j -= 1;
}
}
return ans;
}