-
Notifications
You must be signed in to change notification settings - Fork 0
/
insertion_sort.c
40 lines (31 loc) · 944 Bytes
/
insertion_sort.c
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
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr, i, temp, j, max;
printf("Enter the number of elements in the array: ");
scanf("%d", &max);
// Allocating memory
arr = (int *)(malloc(max * sizeof(int)));
// Receiving elements
printf("Enter %d elements of your array: \n", max);
for(i = 0; i < max; i++) {
scanf("%d", &arr[i]);
}
/* Insertion Sort Algorithm, change '>' to '<' for descending order */
for(i = 1; i < max; i++) {
for(j = 0; j <= (i-1); j++) {
if(arr[j] > arr[i]) {
// Swap the contents of location I and J
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
printf("\n\nSorted Array: \n");
// Displaying new array
for(i = 0; i < max; i++) {
printf("%d\n", arr[i]);
}
return 0;
}