pleae give a logical excplanation of the code i have here. (1 paragraph) Inserti
ID: 3699292 • Letter: P
Question
pleae give a logical excplanation of the code i have here. (1 paragraph)
Insertion sort code
#include <stdio.h>
void insertion_sort(int a[], int n)
{
int i, temp, j;
for(int i=1; i<n; i++)
{
temp = a[i];
j = i-1;
while(j>=0 && a[j] > temp)
{
a[j+1] = a[j];
j = j- 1;
}
a[j+1] = temp;
}
}
int main()
{
int a[1000];
int n;
int i;
printf("Enter no of elements ");
scanf("%d",&n);
printf("Enter elements ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
insertion_sort(a,n);
printf("After sorting ");
for(i=0;i<n;i++)
printf("%d ",a[i] );
}
Explanation / Answer
Logic of Insertion Sort
Insertion sort is one input element each repetition. For Example, I am taken 5 unsorted array elements are (a[7, 3, 1, 10, 5]).
for loop i=1(second element in the array) to 5 (size of an array).
i=1. 3 is smaller than 7, then move 7 and insert 3 before 7, then array is
a[3,7,1,10,5]
i=2. 1 will move to the begining and all othe elements from 3 to 1 will move one position ahead, then
a[1,3,7,10,5]
i=3. 10 will remain at its positin as all elements in array "a" are smaller than 10
i=4. 5 will move to position after 3 then elements are
a[1,3,5,7,10] these are the sorted elements
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.