在前文我们学习了通过冒泡排序法对数字的排序。
本题需要对字符串进行冒泡排序操作。
对字符串冒泡排序涉及的函数为
compareTo()
str1.compareTo(str2)
/*对str1和str2字符串从第一位开始比较,
if( str1 > str2 ) 返回值 > 0
if( str1 < str2 ) 返回值 < 0
if( str1 = str2 ) 返回值 = 0
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int nums = in.nextInt();
int times = in.nextInt();
String[] str = new String[nums];
String temp;
for( int i = 0; i < str.length; i++)
{
str[i] = in.nextLine();
}
for(int i = 0; i < times; i++) //排序次数
{
for(int j = 0; j < nums - i - 1; j++)
{
if(str[j].compareTo(str[j+1]) > 0) //比较str1和str2
{
temp = str[j];
str[j] = str[j+1];