Skip to content

Commit be7b028

Browse files
committed
added insertion sort in c
1 parent 73b81ac commit be7b028

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

InsertionSort/c/InsertionSort.c

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// including liberary
2+
#include <stdio.h>
3+
4+
/*
5+
the algo goes here
6+
*/
7+
void Sort_Array(int arr[], int size) // it will accept interger type array and size of the array
8+
{
9+
// local variable defination
10+
int i, key, j;
11+
for (i = 1; i < size; i++)
12+
{
13+
key = arr[i]; // the i th value
14+
j = i-1; // j is for processing from back
15+
16+
/* Move elements of arr[0..i-1], that are
17+
greater than key, to one position ahead
18+
of their current position */
19+
while (j >= 0 && arr[j] > key) // loop will work till j th value of array is greater than i th value of array and j >= 0
20+
{
21+
arr[j+1] = arr[j];
22+
j--;
23+
}
24+
arr[j+1] = key;
25+
}
26+
}
27+
28+
/*
29+
MAIN FUNCTION
30+
*/
31+
int main() {
32+
// declaring the variable
33+
int size; // size is the array length
34+
int i; // i is for iterations
35+
printf("enter the size of array ");
36+
scanf("%d",&size); // getting size
37+
int array[size]; // declaring array of size entered by the user
38+
39+
// getting value from the user
40+
printf("\nenter values in the array\n");
41+
for (i = 0; i < size; i++) {scanf("%d", &array[i]); }
42+
43+
// printing the original array
44+
printf("\noriginal array -> ");
45+
for (i = 0; i < size; i++) { printf("%d ", array[i]); }
46+
47+
// sorting the array
48+
Sort_Array(array, size);
49+
50+
// printing the sorted array
51+
printf("\nsorted array -> ");
52+
for (i = 0; i < size; i++) { printf("%d ", array[i]); }
53+
54+
return 0;
55+
}
56+

0 commit comments

Comments
 (0)