-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathinsertion_sort.c
More file actions
50 lines (39 loc) · 848 Bytes
/
insertion_sort.c
File metadata and controls
50 lines (39 loc) · 848 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
#include <stdio.h>
#include <stdlib.h>
/**
* Insertion sort algorithm.
*
* @param int input Array to sort
* @param int n Number of data in search array
*
* @return void
*/
void insertion_sort(int *input, int n)
{
int gap, key;
for (int i = 1; i < n; i++) {
key = input[i];
gap = i - 1;
while (gap >= 0 && input[gap] > key) {
input[gap + 1] = input[gap];
gap--;
}
input[gap + 1] = key;
}
}
int main()
{
int n;
printf("How many numbers? ");
scanf("%d", &n);
int *input = (int *) malloc(n * sizeof(int));
printf("Enter %d numbers: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", input + i);
}
insertion_sort(input, n);
for (int i = 0; i < n; i++) {
printf("%d\t", *(input + i));
}
free(input);
}