以下是我的导师提出的问题:
这些是您将使用的数据项: 本田,雪佛兰,福特,劳斯莱斯,梅赛德斯奔驰
import java.util.Scanner;
public class Example532 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String[] list = new String[5];
System.out.println("Enter data: ");
for (int i=0; i<5; i++) {
list[i] = scan.nextLine();
}
System.out.println("Current data:");
for (int i=0; i<5; i++) {
System.out.println(list[i]);
}
// call selection sort
doSelectionSort(list);
// print out current array
System.out.println("Sorted data:");
for (int i=0; i<5; i++) {
System.out.println(list[i]);
}
// call bubble sort
doBubbleSort(list);
System.out.println("Bubble Sorted data:");
for (int i = 0; i < 5; i++) {
System.out.println(list[i]);
}
}
public static String[] doSelectionSort(String[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j].compareTo(arr[index]) < 0)
index = j;
String smaller = arr[index];
arr[index] = arr[i];
arr[i] = smaller;
}
return arr;
}
public static void doBubbleSort(String[] arr) {
boolean swapped = true;
int j = 0;
String tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < arr.length - j; i++) {
if (arr[i].compareTo(arr[i + 1]) < 0) {
tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
swapped = true;
}
}
}
}
}
答案 0 :(得分:0)
按长度排序,而不是
if (arr[j].compareTo(arr[index]) < 0)
使用:
if (arr[j].length() < arr[index].length())
(您需要在多个地方进行此更新。)