/* First let me tell you some basic about insertion sort (for those who wants to refresh there concepts). Its a sorting technique which have a time complexity in worst case as O(n*n) an best case is O(n);*/
/*also i did not utilize the argument of printArr() ,which can be utilized for displaying and knowing the pass number*/
#include<stdio.h>
#include<math.h>
int n,arr[10];
//function to print the elements in the array
void printArr(int a){
int j;
for(j=0;j<n;j++)
printf(" %d",arr[j]);
}
int main(){
int i,j,k;
printf("Enter number of elements");
scanf("%d",&n);
//taking input
for(i=0;i<n;i++){
printf("Enter element %d",i+1);
scanf("%d",&arr[i]);
}
printArr(0);//simply print input array
//doing the insertion sort and displaying every pass result
for(i=0;i<n;i++){
k=arr[i];
j=i-1;
while(j>=0&&k<arr[j]){
arr[j+1]=arr[j];
j--;
}
arr[j+1]=k;
printf("\n");
printArr(i+1);
}
return 0;
}
/*also i did not utilize the argument of printArr() ,which can be utilized for displaying and knowing the pass number*/
#include<stdio.h>
#include<math.h>
int n,arr[10];
//function to print the elements in the array
void printArr(int a){
int j;
for(j=0;j<n;j++)
printf(" %d",arr[j]);
}
int main(){
int i,j,k;
printf("Enter number of elements");
scanf("%d",&n);
//taking input
for(i=0;i<n;i++){
printf("Enter element %d",i+1);
scanf("%d",&arr[i]);
}
printArr(0);//simply print input array
//doing the insertion sort and displaying every pass result
for(i=0;i<n;i++){
k=arr[i];
j=i-1;
while(j>=0&&k<arr[j]){
arr[j+1]=arr[j];
j--;
}
arr[j+1]=k;
printf("\n");
printArr(i+1);
}
return 0;
}
No comments:
Post a Comment