Quick Sort
package iteration;
public interface Iterable {
public Iterator iterator();
}
package dataStructures;
import iteration.Iterable;
public interface List extends Iterable {
public void insert(int index, Object value)
throws IndexOutOfBoundsException;
public void add(Object value);
public Object delete(int index) throws IndexOutOfBoundsException;
public boolean delete(Object value);
public void clear();
public Object set(int index, Object value)
throws IndexOutOfBoundsException;
public Object get(int index) throws IndexOutOfBoundsException;
public int indexOf(Object value);
public boolean contains(Object value);
public int size();
public boolean isEmpty();
}
package sorting;
import dataStructures.List;
public interface ListSorter {
public List sort(List list);
}
package sorting;
import dataStructures.List;
public class QuicksortListSorter implements ListSorter {
private final Comparator _comparator;
public QuicksortListSorter(Comparator comparator) {
assert comparator != null : "comparator cannot be null";
_comparator = comparator;
}
public List sort(List list) {
assert list != null : "list cannot be null";
quicksort(list, 0, list.size() - 1);
return list;
}
private void quicksort(List list, int startIndex, int endIndex) {
if (startIndex < 0 || endIndex >= list.size()) {
return;
}
if (endIndex <= startIndex) {
return;
}
Object value = list.get(endIndex);
int partition = partition(list, value, startIndex, endIndex - 1);
if (_comparator.compare(list.get(partition), value) < 0) {
++partition;
}
swap(list, partition, endIndex);
quicksort(list, startIndex, partition - 1);
quicksort(list, partition + 1, endIndex);
}
private int partition(List list, Object value, int leftIndex, int rightIndex) {
int left = leftIndex;
int right = rightIndex;
while (left < right) {
if (_comparator.compare(list.get(left), value) < 0) {
++left;
continue;
}
if (_comparator.compare(list.get(right), value) >= 0) {
--right;
continue;
}
swap(list, left, right);
++left;
}
return left;
}
private void swap(List list, int left, int right) {
if (left == right) {
return;
}
Object temp = list.get(left);
list.set(left, list.get(right));
list.set(right, temp);
}
}