-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathinsertion_sort.c
68 lines (62 loc) · 1.46 KB
/
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
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
68
/* Program to implement Insertion Sort
* The insertion sort algorithm is a simple sorting algorithm which sorts the array by shifting elements one by one.
*
* Example:
* Enter 4 elements of the array: 12 11 13 5
* Sorted array:
* 5 11 12 13
*
* Enter the number of elements in the array: 120
* Please enter value less than 100
* Enter the number of elements in the array:
*/
#include <stdio.h>
#define MAX_SIZE 100
void insertion_sort(int arr[], int);
void printArray(int arr[], int);
int main(void)
{
int arr[MAX_SIZE];
int size_array;
do
{
printf("Enter the number of elements in the array: ");
scanf("%d", &size_array);
if(size_array > MAX_SIZE)
{
printf("Please enter value less than 100\n");
}
} while(size_array > MAX_SIZE);
printf("Enter %d elements of the array: ", size_array);
for(int i = 0; i < size_array; i++)
{
scanf("%d", &arr[i]);
}
insertion_sort(arr, size_array);
printf("Sorted array:\n");
printArray(arr, size_array);
return 0;
}
void insertion_sort(int arr[], int n)
{
int i, j, key;
for(i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
while(j >= 0 && arr[j] > key)
{
arr[j+1] = arr[j];
j = j - 1;
}
arr[j+1] = key;
}
}
void printArray(int arr[], int n)
{
for(int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}