我从用户那里扫描了字符串。下一步是按文本长度对数组进行排序,我不知道我做错了什么,有时候它正在工作。
public static void quickSort(String[] subtitles, int start, int end) {
int i = start;
int j = end;
if (j - i >= 1) {
String pivot = subtitles[i];
while (j > 1) {
while (subtitles[i].compareTo(pivot) <= 0 && i < end && j > i)
i++;
while (subtitles[j].compareTo(pivot) >= 0 && j > start && j >= i)
j--;
if (j > i)
swap(subtitles, i, j);
}
swap(subtitles, start, j);
quickSort(subtitles, start, j - 1);
quickSort(subtitles, j + 1, end);
} else
return;
}
public static void swap(String[] a, int i, int j) {
String tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amountStrings = 3;
String[] subtitles = new String[amountStrings];
System.out.println("insert ");
for (int i = 0; i < amountStrings; i++) {
subtitles[i] = scan.next();
}
System.out.println("--------");
quickSort(subtitles, 0, subtitles.length - 1);
for (int i = 0; i < subtitles.length; i++) {
System.out.print(subtitles[i] + " ");
}
不正确:
在: asdzxc asd zxc
输出: asd asdzxc zxc
正确:
在: sdf sdfsfwer s 出:
s sdf sdfsfwer
答案 0 :(得分:1)
好的,我查看了您的代码并制作了两种新方法。按字母顺序对数组进行排序,然后通过计算数组中每个单词中的字母数来排序。你有什么方法适合你。 经过测试和工作。
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Subtitles {
public static void sortAlfabetical(String x[]) {
int j;
boolean found = true; // will determine when the sort is finished
String temp;
while (found) {
found = false;
for (j = 0; j < x.length - 1; j++) {
if (x[j].compareToIgnoreCase(x[j + 1]) > 0) { // ascending sort
temp = x[j];
x[j] = x[j + 1]; // swap
x[j + 1] = temp;
found = true;
}
}
}
for (int i = 0; i < x.length; i++) {
System.out.print(x[i] + " ");
}
}
public static void compare(String[] arrayOne) {
Arrays.sort(arrayOne, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
});
for (String s : arrayOne) {
System.out.print(s + " ");
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amountStrings = 3;
String[] subtitles = new String[amountStrings];
System.out.println("insert ");
for (int i = 0; i < amountStrings; i++) {
subtitles[i] = scan.next();
}
System.out.println("--------");
System.out.print("Sorting alphabetical: ");
sortAlfabetical(subtitles);
System.out.println();
System.out.println("===========================");
System.out.print("Sorting by word length: ");
compare(subtitles);
}
}