Sunday 20 March 2011

Java Quicksort

The following is a Java implementation of the basic Quicksort that I threw together to get a better feel for it.  Feel free to use it as you'd like or leave a comment if you see any problems or know a better way to do it.


public static List<Integer> quickSort(List<Integer> list)
{
//Take the last element as the "pivot" point
Integer pivot = list.remove(list.size() - 1);

List<Integer> pre = new ArrayList<Integer>();
List<Integer> post = new ArrayList<Integer>();

//Add each element into the appropriate list, depending on comparison
//to the pivot element
for (Integer i : list)
{
if (i > pivot)
{
post.add(i);
}
else
{
pre.add(i);
}
}

//Now quickSort both the lists
//Then combine the pre list to the pivot to the post list
List<Integer> finalList = new ArrayList<Integer>();
if (pre.size() > 0)
finalList.addAll(quickSort(pre));
finalList.add(pivot);
if (post.size() > 0)
finalList.addAll(quickSort(post));

return finalList;
}

No comments:

Post a Comment