I can't figure out how to correct the program. I have tried changing the Sorting.java program to public static void selectionSort (int[] intList), but that doesn't seem to fix it. Can someone help?
The file Sorting.java contains the Sorting class. This class implements both the selection sort and the insertion sort algorithms for sorting any array of Comparable objects in ascending order. In this exercise, you will use the Sorting class to sort several different types of objects.
The file Numbers.java reads in an array of integers, invokes the selection sort algorithm to sort them, and then prints the sorted array. Save Sorting.java and Numbers.java to your directory. Numbers.java won't compile in its current form. Study it to see if you can figure out why.
Try to compile Numbers.java and see what the error message is. **The problem involves the difference between primitive data and objects. Change the program so it will work correctly (note: you don't need to make many changes - the autoboxing feature of Java 1.5 will take care of most conversions from int to Integer).
Here's the code: -
// Demonstrates the selection sort and insertion sort algorithms.
public class Sorting {
// Sorts the specified array of objects using the selection
// sort algorithm.
public static void selectionSort (Comparable[] list) {
int min;
Comparable temp;
for (int index = 0; index < list.length-1; index++) {
min = index;
for (int scan = index+1; scan < list.length; scan++)
if (list[scan].compareTo(list[min]) < 0)
min = scan;
// Swap the values
temp = list[min];
list[min] = list[index];
list[index] = temp;
}
}
// Sorts the specified array of objects using the insertion
// sort algorithm.
public static void insertionSort (Comparable[] list) {
for (int index = 1; index < list.length; index++) {
Comparable key = list[index];
int position = index;
// Shift larger values to the right
while (position > 0 && key.compareTo(list[position-1]) < 0) {
list[position] = list[position-1];
position--;
}
list[position] = key;
}
}
}
// Numbers.java
// Demonstrates selectionSort on an array of integers.
import java.util.Scanner;
public class Numbers {
// Reads in an array of integers, sorts them,
// then prints them in sorted order.
public static void main (String[] args) {
int[] intList;
int size;
Scanner scan = new Scanner(System.in);
System.out.print ("\nHow many integers do you want to sort? ");
size = scan.nextInt();
intList = new int[size];
System.out.println ("\nEnter the numbers...");
for (int i = 0; i < size; i++)
intList[i] = scan.nextInt();
Sorting.selectionSort(intList);
System.out.println ("\nYour numbers in sorted order...");
for (int i = 0; i < size; i++)
System.out.print(intList[i] + " ");
System.out.println ();
}
}