编写一个Java程序,使用for循环对字符串数组项目进行冒泡排序。为了执行冒泡排序,我们必须比较相邻的字符串,如果它们不是按升序排列,就将它们交换。
package RemainingSimplePrograms;
public class BubbleSortString1 {
public static void main(String\[\] args) {
int i, j;
String\[\] str = {"Java", "Python", "C", "SQL", "Tableau"};
String temp;
System.out.println("Sorting String using the Bubble Sort");
for(i = 0; i < str.length; i++)
{
for(j = 0; j < str.length - i - 1; j++)
{
if(str\[j + 1\].compareTo(str\[j\]) > 0)
{
temp = str\[j\];
str\[j\] = str\[j + 1\];
str\[j + 1\] = temp;
}
}
System.out.println(str\[j\]);
}
}
这是另一个对字符串进行泡沫排序的Java例子。
package RemainingSimplePrograms;
public class BubbleSortString2 {
public static void main(String\[\] args) {
int i, j;
String\[\] str = {"Java", "Python", "C", "SQL", "Tableau"};
String temp;
for(j = 0; j < str.length; j++)
{
for(i = j + 1; i < str.length; i++)
{
if(str\[i\].compareTo(str\[j\]) < 0)
{
temp = str\[j\];
str\[j\] = str\[i\];
str\[i\] = temp;
}
}
System.out.println(str\[j\]);
}
}
C
Java
Python
SQL
Tableau