-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertion-sort.c
More file actions
67 lines (53 loc) · 925 Bytes
/
insertion-sort.c
File metadata and controls
67 lines (53 loc) · 925 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int *gen_rand_nums(int n);
void print_nums(int *nums, int n);
void insertion_sort(int *nums, int n);
int main()
{
int n;
scanf("%d", &n);
int *nums = gen_rand_nums(n);
printf("Before: ");
print_nums(nums, n);
insertion_sort(nums, n);
printf("After: ");
print_nums(nums, n);
free(nums);
}
void print_nums(int *nums, int n)
{
for (int i = 0; i < n; i++)
{
printf("%d ", nums[i]);
}
printf("\n");
}
int *gen_rand_nums(int n)
{
int *nums = (int *)calloc(n, sizeof(int));
for (int i = 0; i < n; i++)
{
nums[i] = 1 + rand() % 101;
}
return nums;
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void insertion_sort(int *nums, int n)
{
for (int i = 0; i < n; i++)
{
int j = i;
while (j > 0 && nums[j - 1] > nums[j])
{
swap(&nums[j], &nums[j - 1]);
j--;
}
}
}