-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertion_sort.cpp
More file actions
45 lines (37 loc) · 781 Bytes
/
insertion_sort.cpp
File metadata and controls
45 lines (37 loc) · 781 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
#include <iostream>
#define MAX_SIZE 101
void insertion_sort(int *list, int n) {
int key = 0;
int i = 0;
int j = 0;
for (int i = 1; i < n; i++) {
key = list[i];
j = i - 1;
while (j >= 0 && list[j] > key) {
list[j+1] = list[j];
j = j - 1;
}
list[j+1] = key;
}
}
int main(void) {
int i, n;
int list[MAX_SIZE];
printf("Enter the number of numbers to generate: ");
scanf("%d", &n);
if ( n < 1 || n > MAX_SIZE) {
fprintf(stderr, "Improper value of n\n");
exit(-1);
}
for (i = 0; i < n; i++) {
list[i] = rand() % 1000;
printf("%d ", list[i]);
}
printf("\n");
insertion_sort(list, n);
printf("\nSorted array:\n");
for (i = 0; i < n; i++)
printf("%d ", list[i]);
printf("\n");
return 0;
}