Skip to content

Commit d4afcd3

Browse files
Create 36.1 String Sorting Bubble Sort.java
1 parent b9458a1 commit d4afcd3

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

36.1 String Sorting Bubble Sort.java

+89
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
/*
2+
Write a program to take "n" String inputs from user and store them in array (where "n" is no. of String objects specified by user at run-time). Sort the array in ascending order and display the array. If "n" entered by user is less than 2, then display message "Invalid".
3+
4+
Input Format
5+
6+
Your program should take the input of "n" string objects.
7+
8+
Constraints
9+
10+
No. of string objects entered by the user should be greater than 1.
11+
12+
Output Format
13+
14+
Your program should display the array of strings in sorted ascending order.
15+
16+
Sample Input 0
17+
18+
4
19+
India
20+
America
21+
Australia
22+
France
23+
Sample Output 0
24+
25+
America
26+
Australia
27+
France
28+
India
29+
*/
30+
import java.io.*;
31+
import java.util.*;
32+
33+
public class CLASS
34+
{
35+
36+
public static void main(String[] args) {
37+
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
38+
Scanner sc = new Scanner(System.in);
39+
int n = sc.nextInt();
40+
if(n>=2)
41+
{
42+
String []s = new String[n];
43+
for(int i=0;i<n;i++)
44+
{
45+
s[i] = sc.next();
46+
}
47+
for(int i=0;i<n-1;i++)
48+
{
49+
for(int j=0;j<n-1-i;j++)
50+
{
51+
52+
int k=0,l=0;
53+
while(k<s[j].length() && l<s[j+1].length())
54+
{
55+
if(s[j].charAt(k) > s[j+1].charAt(l))
56+
{
57+
String temp = s[j];
58+
s[j] = s[j+1];
59+
s[j+1] = temp;
60+
break;
61+
}
62+
else if(s[j].charAt(k) < s[j+1].charAt(l))
63+
{
64+
break;
65+
}
66+
else if(s[j+1].length() == l+1)
67+
{
68+
String temp = s[j];
69+
s[j] = s[j+1];
70+
s[j+1] = temp;
71+
break;
72+
}
73+
k++;l++;
74+
}
75+
76+
}
77+
}
78+
for(int i=0;i<n;i++)
79+
{
80+
System.out.println(s[i]);
81+
}
82+
}
83+
else
84+
{
85+
System.out.print("Invalid");
86+
}
87+
88+
}
89+
}

0 commit comments

Comments
 (0)