0
import java.io.File;
import java.util.Scanner;
public class TestDriver {
public static void main(String[] args) {
Scanner x = null;
try {
x = new Scanner(new File("pokemon"));
} catch (Exception e) {
System.out.println("could not find file");
}
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.println("Type in the number of Pokemons (1-15)!");
int userNumber = 0;
boolean userFalse = false;
while (!userFalse) { // Validates user inputs for years
if (input.hasNextInt()) {
int temp = input.nextInt();
if (temp < 1 || temp > 15) { // Years cannot be below 0
System.out.println("Invalid input.");
userFalse = false;
} else {
userFalse = true;
userNumber = temp;
}
} else {
System.out.println("Try Again!");
input.next();
}
}
String[] a = new String[userNumber];
for (int i = 0; i < userNumber; i++) {
a[i] = x.next();
System.out.print(a[i] + " ");
}
sort(a, userNumber);
}
在pokemon.txt,它讀取如何使用遞歸排序從最小到最大的字符串數組?
Gyarados
Lapras
Eevee
Vaporeon
Snorlax
Abra
Slowbro
Rhyson
Kyogre
Blastoise
Jigglypuff
Miltank
Lugia
Steelix
Arbok
我想口袋妖怪編號排序,從最小到最大。我不知道這樣做的最好方法。我的老師讓我用遞歸來做。這與quicksort或mergesort是一樣的嗎?提前致謝。 編輯:這是我嘗試使用歸併排序:
public static void sort(String[] pokemon, int userNumber) {
String[] a = new String[pokemon.length/2]; // Split array into two
String[] b = new String[pokemon.length - a.length]; // halves, a and b
for (int i = 0; i < pokemon.length; i++) {
if (i < a.length)
a[i] = a[i];
else
b[i - a.length] = pokemon[i];
}
sort(a, userNumber); // Recursively sort first
sort(b, userNumber); // and second half.
int ai = 0; // Merge halves: ai, bi
int bi = 0; // track position in
while (ai + bi < pokemon.length) { // in each half.
if (bi >= b.length || (ai < a.length && a[ai].length() < b[bi].length())) {
pokemon[ai + bi] = a[ai]; // (copy element of first array over)
ai++;
} else {
pokemon[ai + bi] = b[bi]; // (copy element of second array over)
bi++;
}
}
}
在這裏你可以找到一個類似的問題 [鏈接](http://stackoverflow.com/questions/29503987/recursive-sorting-an-array-a-specific-way/29504431#29504431) –
它不清楚你的代碼...你是否嘗試排序文件或用戶輸入?你什麼都沒有顯示與任何排序方法有關我會說谷歌是你的朋友在這裏...查找遞歸快速排序或這樣的。 – JohnG
這是很多代碼,有*沒有*與您的問題。請刪除任何不必要的代碼。 – Andreas