
Originally Posted by
kaka1994
A. The Java program below is intended to sort an array of String objects. Complete the program by implementing the selectionSort function for arrays. A demo program from chapter 8 is provided with the assignment as an example of how to implement selection sort for an array of integers.
public static void main(String[] args)
{
String[] names = {"Joseph", "Aya", "Sally",
"Mohammad", "Ragda", "Bayan"};
// Display the unsorted array.
System.out.println("The unsorted values are:");
for (int i = 0; i < names.length; i++)
System.out.println(names[i] + " ");
System.out.println();
// Sort the array.
selectionSort(names);
// Display the sorted array.
System.out.println("The sorted values are:");
for (int i = 0; i < names.length; i++)
System.out.println(names[i] + " ");
}
B. Write a program to sort a list of names read from a text file. One challenge with this program is to determine the number of names in a file.
I have done part A help but I don't know how to do part B
part A :
public static void main(String[] args)
{
String[] names = {"Joseph", "Aya", "Sally",
"Mohammad", "Ragda", "Bayan"};
// Display the unsorted array.
System.out.println("The unsorted values are:");
for (int I = 0; I < names.length; I++) {
System.out.println(names[i] + " ");
}
System.out.println();
// Sort the array.
selectionSort(names);
// Display the sorted array.
System.out.println("The sorted values are:");
for (int I = 0; I < names.length; I++) {
System.out.println(names[i] + " ");
}
System.out.println();
}
static void selectionSort(Comparable[] names)
{
int smallindex;
for(int I = 0; I < names.length; I++)
{
smallindex = I; // set first element as smallest
for(int j = I + 1; j < names.length; j++) {
if(names[j].compareTo(names[smallindex]) < 0) {
smallindex = j;
}
}
if(smallindex != I) {
swap(names, smallindex, I);
}
}
}
// Swap for two elements of an array of Objects
//index1 the index of the first element to swap
// index2 the index of the second element to swap
static void swap(Object[] names, int index1, int index2)
{
Object temp = names[index1];
names[index1] = names[index2];
names[index2] = temp;
}
}