The insertion sort algorithm is a more efficient means of sorting an array than
ID: 3547046 • Letter: T
Question
The insertion sort algorithm is a more efficient means of sorting an array than the selection sort. This algorithm is analogous to the procedure that card players follow when picking up cards and inserting them in their hand to form a run in a particular suit. A player makes room for a new card by shifting over the ones that follow it and then inserting it where it belongs in the hand. In sorting an array, all values are available when you begin, but you can assume that the array is not sorted and start by inserting the value currently in the second array element by comparing it to the first element. This gives you a sorted subarray consisting of the first two elements. Next, you insert the value currently in the third array element where it belongs compared to the first two, which gives you a sorted subarray of three elements, and so on. You
Explanation / Answer
#include<stdio.h>
using namespace std;
int main()
{
int n;
int a[1000];
scanf("%d",&n);
for(int z=1;z<=n;z++){
scanf("%d",&a[z]);
}
for(int j=2;j<=n;j++){
int key=a[j];
for(int i=1;i<j;i++){
if(a[i]>a[j]){
int temp;
temp=a[j];
a[j]=a[i];
a[i]=temp;
}
}
for (int z=1;z<=n;z++){
printf("%d ",a[z]);
}
printf(" ");
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.