Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a method insertionSort that sorts the values from smallest value to the la

ID: 3681295 • Letter: W

Question

Write a method insertionSort that sorts the values from smallest value to the largest. The method should compare the two closest values, and shift them according to the value, shifting the bigger value to the right, the method should do to all the values until all the list is arranged from the lowest to the largest. For example; 22 and 18, the method will shift 18 to the left. Then will compare 22 and 12, then shift 12 to the left or 22 to the right. But for the values that belong on that spot, will just leave them. index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 value 22 18 12 -4 27 30 36 50 7 68 91 56 2 85 42 98 25

Explanation / Answer

/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n)
{
int i,key,j;
for(i=1;i<n;i++)
{
key=arr[i];
j=i-1;

/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while(j>=0 && arr[j]>key)
{
arr[j+1]=arr[j];
j=j-1;
}
arr[j+1]=key;
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote