51.8k views
1 vote
Write a client program ClientSorting2 and in the main() method: 1. Write a modified version of the selection sort algorithm (SelectionSorter()) that sorts an array of 23 strings (alphabetically) rather than one of integer values. Print the array before it is sorted in the main() method, then after it is sorted in SelectionSorter().

User Nogoseke
by
3.2k points

1 Answer

4 votes

Answer:

The program in Java is as follows:

import java.util.*;

public class Main{

public static void SelectionSorter(String[] my_array){

System.out.print("\\After sort: ");

for (int ind=0; ind < 22; ind++ ){

int min = ind;

for (int k=ind+1; k < 23; k++ )

if (my_array[k].compareTo(my_array[min] ) < 0 ){ min = k; }

String temp = my_array[ind];

my_array[ind] = my_array[min];

my_array[min] = temp; }

for (int j=0; j < 23; j++){ System.out.print(my_array[j]+" ");}

}

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

String [] myarray = new String [23];

for(int i= 0;i<23;i++){ myarray[i] = input.nextLine(); }

System.out.print("Before sort: ");

for ( int j=0; j < 23; j++ ){ System.out.print(myarray[j]+" "); }

SelectionSorter(myarray);

}

}

Step-by-step explanation:

This defines the function

public static void SelectionSorter(String[] my_array){

This prints the header for After sort

System.out.print("\\After sort: ");

This iterates through the array

for (int ind=0; ind < 22; ind++ ){

This initializes the minimum index to the current index

int min = ind;

This iterates from current index to the last index of the array

for (int k=ind+1; k < 23; k++ )

This compares the current array element with another

if (my_array[k].compareTo(my_array[min] ) < 0 ){ min = k; }

If the next array element is smaller than the current, the elements are swapped

String temp = my_array[ind];

my_array[ind] = my_array[min];

my_array[min] = temp; }

This iterates through the sorted array and print each array element

for (int j=0; j < 23; j++){ System.out.print(my_array[j]+" ");}

}

The main begins here

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

This declares the array

String [] myarray = new String [23];

This gets input for the array elements

for(int i= 0;i<23;i++){ myarray[i] = input.nextLine(); }

This prints the header Before sort

System.out.print("Before sort: ");

This iterates through the array elements and print them unsorted

for ( int j=0; j < 23; j++ ){ System.out.print(myarray[j]+" "); }

This calls the function to sort the array

SelectionSorter(myarray);

}

}

User Intelekt
by
4.0k points