Over the Christmas break I had plans to create a number of Java class for a variety of sorting algorithms. Part of this was to remind me of my early days in learning to code but also to eventually build a sorting demonstration tool such as this Android app I found recently called Sorts. Fortunately there were far better things to do over the break then program, as such it was not until recently that I had a chance to start on this task.
My desire was to create a class for each algorithm with the needed functions. The main function in this class should allow for any object that implements comparable so that these sorting algorithms are as universal as possible (a slight modification from my early days). However this was an area of working with Java that I have not had much practise in (that being to make use of generic in Java). As such after various articles found via Google I was able to come up with the following implementation of a simple QuickSort (I still need to figure out how to add some form of a demo layer).
package org.oavatos.sorting.algorithims;
import java.util.ArrayList;
import java.util.Arrays;
public class QuickSort<E extends Comparable<E>> {
public ArrayList<E> simple(ArrayList<E> data) {
if (data.size() <= 1) {
return data;
}
ArrayList<E> alLess = new ArrayList<E>();
ArrayList<E> alMore = new ArrayList<E>();
ArrayList<E> alAll = new ArrayList<E>();
E pivot = data.remove(data.size() / 2);
for (int i = 0; i < data.size(); i++) {
if (data.get(i).compareTo(pivot) <= 0) {
alLess.add(data.get(i));
} else {
alMore.add(data.get(i));
}
}
// Put the arraylist back together
alAll.addAll(simple(alLess));
alAll.add(pivot);
alAll.addAll(simple(alMore));
return alAll;
}
public static void main(String[] args) {
Long[] myInts = { 11l, 6l, 3l, 8l, 9l, -1l, 23l, 8l, 0l, -2l };
/**
* Simple quick sort
*/
System.out.println("QuickSort: Simple");
ArrayList<Long> alData = new ArrayList<Long>();
alData.addAll(Arrays.asList(myInts));
}
}