Prelude to Programming6th Edition Chapter 8 Short Answer 18
Prelude to Programming(6th Edition) Chapter 8 Short Answer 18.
Please use Pseudocode only.
For Short Answer Question refer to the following array: Write a program segment to sort the given array in alphabetical order Using the bubble sort method.Solution
import java.util.*;
public class sortNames {
public static void main(String args[]) {
Please enter 10 names
greg
larry
tom
william
john
brett
camille
ian
terry
audrey
The sorted array is:
names[0] is: audrey
names[1] is: brett
names[2] is: camille
names[3] is: greg
names[4] is: ian
names[5] is: john
names[6] is: larry
names[7] is: terry
names[8] is: tom
names[9] is: william
String[] names= new String[10];
Scanner in = new Scanner(System.in);
String temp;
System.out.println(\"Please enter 10 names\");
for (int i=0; i<names.length; i++)
names[i]= in.nextLine();
// make N-1 passes through the array
for (int i=1; i < names.length; i++) {
// compare N-1 pairs of elements.
for (int j = 0; j < (names.length-1); j++) {
if ( (names[j].compareTo(names[j+1])) > 0 ) {
temp = names[j];
names[j] = names[j+1];
names[j+1] = temp;
} // end if
} // end inner for
} // end outer for
System.out.println(\"The sorted array is: \");
for (int i=0; i<names.length; i++)
System.out.println(\"names[\" + i + \"] is: \" + names[i]);
} // end main
} // end class
|


