The insertion sort algorithm works by assuming that the array is already sorted
ID: 3619714 • Letter: T
Question
The insertion sort algorithm works by assuming that the array is already sorted and its job is to take each new value and insert it into the appropriate place in the array. Starting the new value a [1] becomes the index and is compared with the previous element in the array a [ 0 ]. If the new value a [j] is smaller that the previous a (j-1], copy a [ j - 1 ] to and decrement j. This is repeated until j = 0 or a [ j ] becomes larger than a[j-1]. When j = 0 or the new number is finally larger than some value in the array, it is the appropriate place to insert it. If the new value a [ j ] is larger than the previous a [ j-1], copy the index value to a [ j ] , increment i and make j equal to it. This continues until i become equal to SIZE. Write a function interSort that uses the algorithm above to sort numbers from the smallest to largest.Explanation / Answer
please rate -thanks #include <stdio.h>#include<conio.h>
void insertSort(int[], int*, int);
int main()
{int array[20];
int i,length=0,value;
printf("What value would you like to add to the array?(-999 when done) ");
scanf("%d",&value);
while(value!=-999)
{
insertSort(array,&length,value);
printf("array ");
for(i=0;i<length;i++)
printf("%d ",array[i]);
printf(" ");
printf("What value would you like to add to the array?(-999 when done) ");
scanf("%d",&value);
}
getch();
return 0;
}
void insertSort(int array[],int* length,int value)
{int i,j;
if(*length>0)
{for(i=0;i<*length;i++)
if(value<array[i])
{for(j=*length;j>i;j--) //move all elements down 1
array[j]=array[j-1];
array[i]=value;
*length=*length+1;
return;
}
}
array[*length]=value;
*length=*length+1;
return;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.