Write a program to input twenty names in an array. Arrange these names in descending order of alphabets ,using bubble sort technique.( Platform:BlueJ )plz tell as soon as possible
Answers
import java.util.*;
public class Alphabetical
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String[] names = new String[5];
System.out.println("Enter 5 names: ");
for (int i = 0; i < 5; i++)
{
names[i] = sc.nextLine();
}
for (int i = 0; i < names.length - 1; i++)
{
for (int j = 0; j < names.length - i - 1; j++)
{
if (names[j].compareTo(names[j + 1]) > 0)
{
String temp = names[j];
names[j] = names[j + 1];
names[j + 1] = temp;
}
}
}
System.out.println("Sorted names: ");
for (int i = 0; i < names.length; i++)
{
System.out.println(names[i]);
}
}
}
Answer:
the above one is correct,
just instead of if (names[j].compareTo(names[j + 1]) > 0) ,
if (names[j].compareTo(names[j + 1]) < 0) is to be used
Explanation:
import java.util.*;
public class arrange_names
{public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String[] names = new String[5];
System.out.println("Enter 5 names: ");
for (int i = 0; i < 5; i++)
{
names[i] = sc.nextLine();
}
for (int i = 0; i < names.length - 1; i++)
{
for (int j = 0; j < names.length - i - 1; j++)/*for (int j = 0; j < names.length - 1; j++) will also work
{
if (names[j].compareTo(names[j + 1]) < 0)
{
String temp = names[j];
names[j] = names[j + 1];
names[j + 1] = temp;
}
}
}
System.out.println("Sorted names: ");
for (int i = 0; i < names.length; i++)
{
System.out.println(names[i]);}
}
}