Quicksort一个字符串的arraylist

时间:2015-11-28 11:48:59

标签: java quicksort

我目前有这个,但我相信它是为整数排序但我需要排序字符串。我怎样才能改变它以适应字符串。

/**
* This method should use a quick sort approach to rearrange
* the references in the ArrayList 'list' such that they are in
* non-decreasing alphabetic order.
* 
* @param list An ArrayList of Vehicle objects that need sorting
* @return  The ArrayList of vehicles that has been sorted using quick sort
*/
protected ArrayList<Vehicle> quickSort(ArrayList<Vehicle> list)
{
    // Use the quick sort algorithm to sort 'vehicles' and then 
    // return it. Initially this method just returns an empty
    // list - you need to fix this.
    ArrayList<Vehicle> sorted = new ArrayList<Vehicle>();
    Vehicle smaller = new Vehicle();
    Vehicle greater = new Vehicle();
    int pivot = list.get(0);
    int i;
    int j;
    for (i = 1; i < list.size(); i++) {
        j = list.get(i);
        if (j.compareTo(pivot) < 0) {
            smaller.add(j);
        } else {
            greater.add(j);
        }
    }
    smaller = quicksort(smaller);
    greater = quicksort(greater);
    smaller.add(pivot);
    smaller.addAll(greater);
    smaller = sorted;

    return sorted;
}

1 个答案:

答案 0 :(得分:3)

添加了一些解释:

public static ArrayList<Vehicle> quickSort(ArrayList<Vehicle> list)
{
    if (list.isEmpty()) 
        return list; // start with recursion base case
    ArrayList<Vehicle> sorted;  // this shall be the sorted list to return, no needd to initialise
    ArrayList<Vehicle> smaller = new ArrayList<Vehicle>(); // Vehicles smaller than pivot
    ArrayList<Vehicle> greater = new ArrayList<Vehicle>(); // Vehicles greater than pivot
    Vehicle pivot = list.get(0);  // first Vehicle in list, used as pivot
    int i;
    Vehicle j;     // Variable used for Vehicles in the loop
    for (i=1;i<list.size();i++)
    {
        j=list.get(i);
        if (j.compareTo(pivot)<0)   // make sure Vehicle has proper compareTo method 
            smaller.add(j);
        else
            greater.add(j);
    }
    smaller=quickSort(smaller);  // capitalise 's'
    greater=quickSort(greater);  // sort both halfs recursively
    smaller.add(pivot);          // add initial pivot to the end of the (now sorted) smaller Vehicles
    smaller.addAll(greater);     // add the (now sorted) greater Vehicles to the smaller ones (now smaller is essentially your sorted list)
    sorted = smaller;            // assign it to sorted; one could just as well do: return smaller

    return sorted;
}