Advertisements
Advertisements
Question
Write a program for the following.
Create a string array ST[ ] to assign the following color names. Arrange the names in ascending order using Bubble Sort -Violet, Indigo, Blue, Green, Yellow, Orange, Red.
[Hint: (StringArray[p].compareTo(StringArray[p + 1]) > 0)indicates a swap is needed]
Code Writing
Advertisements
Solution
import java.util.*;
class clTask
{
void main()
{
String ST[] = {"Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"};
for(int j= 1; j <=ST.length -1; j++)
{
for(int k = 0; k <= ST.length - 2; k++)
{
if(ST[k].compareTo(ST[k + 1]) > 0)
{
String tmp = ST[k];
ST[k] = ST[k + 1];
ST[k+1] = tmp;
}
}
}
System.out.println("In Ascending Order : ");
for(int p = 0; p <= ST.length - 1; p++)
{
System.out.print(" " + ST[p]);
}
}
}
Output:
In Ascending order:
Blue Green Indigo Orange Red Violet Yellow
shaalaa.com
Is there an error in this question or solution?
