Problem Task
Your task is to develop part of a program that sorts array of integers in ascending order
(small to large). The program prompts the user to enter a list of integer numbers then
process them to produce an ascending sorted list as follows.
Enter list of numbers: 1 4 9 7 2
Sorted list: 1 2 4 7 9
please complete the following program -solve problem-(step 4)using this algorithm
Algorithm
To solve this problem you are going to use a modi¯ed version of insertion-sort algorithm
which works as follows:
² Create an empty new list the same size as the given unsorted list of numbers.
² Take the least number from the unsorted list and put it into ¯rst position in the new
list.
² Take the second least number and put it into second position in the new list.
² Repeat until last number which will be the largest number inserted at last position
of new list.
hint: please use this algorithm.
please reply as soon as possible
import java.util.Scanner;
public class InsertionSort {
public static void main(String[] args) {
// data
int[] input; /* array of numbers to sort */
Scanner sc; /* for reading user input */
String line; /* line read from user */
// 1. Read data from user
System.out.print("Enter list of numbers: ");
sc = new Scanner(System.in);
line = sc.nextLine();
// 2. Parse line to create array of numbers
line.trim();
String[] numbers = line.split("\\s");
input = new int[numbers.length];
for(int i=0; i < input.length; i++)
input[i] = Integer.parseInt(numbers[i]);
// 3. Sort the array
int [] sorted = insertionSort(input);
// 4. Print out the results
System.out.print("Sorted list: ");
for(int i = 0; i < sorted.length; i++ )
System.out.print(sorted[i] + " ");
System.out.println();
}
static int [] insertionSort(int[] unsorted) {
int [] sorted = new int [unsorted.length];
/*
*
* complete this method ...
*
*/
return sorted;
}
/*
* This method takes array of numbers and an index
* then it creates new array containing all the
* numbers from the input array excluding the item
* at the specified index.
* The method returns the new array as a result.
*/
static int [] exclude(int [] array, int index) {
int [] newArray = new int [array.length-1];
for(int i=0,j=0; i < newArray.length; j++) {
if (j != index) {
newArray[i] = array[j];
i++;
}
}
return newArray ;
}
}
