-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertion sort function.c
More file actions
68 lines (63 loc) · 1.6 KB
/
Copy pathInsertion sort function.c
File metadata and controls
68 lines (63 loc) · 1.6 KB
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
#include<stdio.h>
void ascend(int a[] ,int n);
void descend(int a[],int n);
int main(){
int n , option;
printf("Enter the no. of elements wants to enter in the array : \n");
scanf("%d",&n);
int a[n];
printf("Enter the %d elements in the array : \n",n);
for(int i=0 ; i<n ; i++){
scanf("%d",&a[i]);
}
printf("Enter 1 for ascending and 2 fro descending: \n ");
scanf("%d",&option);
if(option == 1){
printf("Ascending order is : \n");
ascend(a,n);
}
else if(option == 2){
printf("Descending order is :\n");
descend(a,n);
}
else{
printf("Please read the instruction carefully and then enter here : \n");
}
return 0;
}
void ascend(int a[] ,int n){
int curr ,prev;
//Insertion sort :-
for(int i=1 ; i<n ; i++){
curr =a[i];
prev = i-1;
while(prev >= 0 && a[prev]>curr){
a[prev+1]=a[prev];
prev--;
}
a[prev +1] = curr ;
}
// Printing the sorted array :-
printf("Your sorted array is :\n");
for(int i=0 ; i<n ;i++){
printf("%d \t",a[i]);
}
}
void descend(int a[],int n){
int curr ,prev ;
//Insertion sort :-
for(int i=1 ; i<n ; i++){
curr =a[i];
prev = i-1;
while(prev >= 0 && a[prev]<curr){
a[prev+1]=a[prev];
prev--;
}
a[prev +1] = curr ;
}
// Printing the sorted array :-
printf("Your sorted array is :\n");
for(int i=0 ; i<n ;i++){
printf("%d \t",a[i]);
}
}