Your second task is to implement the Insertion Sort algorithm by making a function with the
following prototype;
void insertion_sort(int * ptr_array, int size, int order);
This function takes as input a pointer to the start of the array, and the array size and sorts it in-
place. The last input to the function is the sorting order (0 for ascending and 1 for descending).
#include<stdio.h>
void insertion_sort(int *ptr_array, int size, int order){
int i,j,t;
for(i=0,i<size;i++){
for(j=i+1;j<size;j++){
if(*(ptr_array+j) < *(ptr_array+i)){
t= *(ptr_array+i);
*(ptr_array+i)=*(ptr_array +j);
*(ptr_array+j)=t;
}
}
}
if(order==1)
for(i=0;i<size;i++)
printf("%d",*(ptr_array+i));
else if(order==0)
for(i=size-1;i>=0;i--)
printf("%d",*(ptr_array+i));
else
printf("please give 0 or 1 only");
}
int main(){
int size;
printf("enter size of array");
scanf("%d",&size);
int order;
printf("enter in 0 or 1 0 for ascending and 1 for descending");
scanf("%d",&order);
int arr[size];
printf("\n enter your element");
for(int i=0;i<size;i++)
scanf("%d",&arr[i]);
insertion_sort(arr,size,order);
return 0;
}
Comments
Leave a comment