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

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

ID: 3680597 • Letter: J

Question

Java

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

package com.java2novice.algos;

public class MyInsertionSort
{
public static void main(String[] args)
{
int[] input = {22, 18, 12, -4, 27, 30, 36, 50, 7, 68, 91, 56, 2, 85, 42, 98, 25};
insertionSort(input);
}
private static void printNumbers(int[] input)
{
for(int i = 0; i<input.length; i++)
{
System.out.print(input[i] + ",");
}
System.println(" ");
}
public static void insertionSort(int array[])
{
int n = array.length;
for(int j = 1; j<n; j++)
{
int key = array[j];
int i = j-1;
while((i > -1) && (array[i] > key))
{
array[i+1] = array[i];
i--;
}
array[i+1] = key;
printNumbers(array);
}
}
}

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