-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathinsert_sort.c
More file actions
51 lines (43 loc) · 816 Bytes
/
insert_sort.c
File metadata and controls
51 lines (43 loc) · 816 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
50
51
/*
* insertion sort
*/
#include <stdio.h>
#define MAX_ELE 50
void insert_sort(int *a, int n) {
int i = 0;
int j = 0;
if (a == NULL || n <= 1) {
return;
}
for (i = 1; i < n; ++i) {
int tmp = a[i];
for (j = i - 1; j >= 0; --j) {
if (a[j] > tmp) {
a[j + 1] = a[j];
}
else {
break;
}
}
a[j + 1] = tmp;
}
return;
}
int main()
{
int n;
int a[MAX_ELE + 1];
int i = 0;
printf("Insert Sort\n");
printf("Number of elements (max %u): ", MAX_ELE);
scanf("%u", &n);
for (; i < n; ++i) {
scanf("%d", &a[i]);
}
insert_sort(a, n);
for (i = 0; i < n; ++i) {
printf("%d ", a[i]);
}
printf("\n");
return 0;
}