如何使用递归对从最小到最大的字符串数组进行排序?

时间:2016-10-31 04:04:43

标签: java algorithm sorting recursion

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

我正在尝试将口袋妖怪NAMES从最小到最大排序。我不知道这样做的最好方法。我的老师要我用递归来做。这与quicksort或mergesort相同吗?提前致谢。 编辑:这是我尝试使用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++;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

Quicksort和Mergesort都可以递归实现。由于这是作业,我不会提供实际的代码,但我会将你链接到一些你可以看的地方:

  1. Merge Sort
  2. Quick Sort