forked from randerson112358/C-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertionSort.c
60 lines (42 loc) · 1021 Bytes
/
InsertionSort.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
/*
This program sorts an array of elements using the insertion sort algorithm
By:randerson112358
Output:
Enter total elements: 3
Enter 3 elements: 9 4 8
After Sorting: 4 8 9
*/
#include <stdio.h>
int insertionSort(int size, int *array);
int main(){
int size, i , array[21];
printf("Enter total number of elements: ");
scanf("%d", &size);
printf("Enter %d elements: ", size);
for(i=0; i<size; i++)
scanf("%d", &array[i]);
//Start sorting the array using the insertion sort algorithm
insertionSort(size, array);
printf("After Sorting: ");
for(i=0; i<size; i++)
printf(" %d", array[i]);
printf("\n");
system("pause"); //Comment this our if you are not using a Windows OS
return 0;
}
int insertionSort(int size, int *array){
int i, j;
int temp;
//Insertion Sort
for(i=1; i<size; i++){
temp=array[i];
j= i-1;
while( (temp < array[j]) && (j >= 0)){
//swap
array[j+1] = array[j];
j= j-1;
}
array[j+1] = temp;
}
return 1;
}