Write a program to assign 10 country names to an array of strings. Sort them in ascending order using Bubble Sort technique.
Answers
Answer:
Program:-
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
String a[]=new String[5];
String temp;
System.out.println("Enter the elements of the array");
for(int i=0;i<a.length;i++)
{
a[i]=in.nextLine();
}
System.out.println("Given Array:");
System.out.println(Arrays.toString(a));
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a.length-1-i;j++)
{
if(a[j].compareTo(a[j+1])>0)
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.println("Sorted Array:");
System.out.println(Arrays.toString(a));
}
}
Output is attched.
Output:
Sorted list is:
Cambodia
India
Japan
Australia
United Kingdom
France
Italy
America
Canada
China
Códe walkthrough:
Line 18. It compares the given two adjacent elements which is at j th position and at of (j+1) position.
Line 20. It stores the value in a temporary variable of a current element.
Line 21. It stores the the value of the next element of a array in a current element.
Line 22. It stores the value of the temporary variable in the next element.
Additional information:
• An array means a group of a specific ordered collection of values that are stored in memory locations.
• Using arrays makes the programming very easiest as compared to traditional primitive types.
___________________By [Yug]