PROBLEM STATEMENT
Write a C program to perform insertion sort on an array of n elements.
Input Format:
Input consists of n+1 integers. The first integer corresponds to n, the number of elements in the array. The next n integers correspond to the elements in the array.
Input consists of n+1 integers. The first integer corresponds to n, the number of elements in the array. The next n integers correspond to the elements in the array.
Sample Input and Output:
[All text in bold corresponds to input and the rest corresponds to output]
[All text in bold corresponds to input and the rest corresponds to output]
Enter the number of elements in the array
5
Enter element 1
4
Enter element 2
2
Enter element 3
7
Enter element 4
3
Enter element 5
1
Insertion sort.
array before sorting:
4 2 7 3 1
After Iteration 1
2 4 7 3 1
After Iteration 2
2 4 7 3 1
After Iteration 3
2 3 4 7 1
After Iteration 4
1 2 3 4 7
array after sorting:
1 2 3 4 7
SOLUTION
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
int main() | |
{ | |
int n,i,j,arr[5],temp; | |
printf("n:"); | |
scanf("%d",&n); | |
for(i=0;i<n;i++){ | |
scanf("%d",&arr[i]); | |
} | |
printf("array before sorting\n"); | |
for(i=0;i<n;i++){ | |
printf("%d ",arr[i]); | |
} | |
for(i=0;i<n-1;i++){ | |
for(j=i+1;j>=0;j--){ | |
if(arr[j]<arr[j-1]){ | |
temp=arr[j]; | |
arr[j]=arr[j-1]; | |
arr[j-1]=temp; | |
} | |
} | |
printf("\nAfter iteration %d\n",i+1); | |
for(j=0;j<n;j++){ | |
printf("%d ",arr[j]); | |
} | |
} | |
printf("\nSorted:\n"); | |
for(i=0;i<n;i++){ | |
printf("%d ",arr[i]); | |
} | |
return 0; | |
} |
OUTPUT
This comment has been removed by the author.
ReplyDelete