所以我一直在测试不同的排序算法,现在我写了一个快速排序!它有点工作,但排序有点偏离!几乎总是我得到这样的输出:
[0, 1, 2, 3, 8, 6, 5, 4, 7, 9, 20, 16, 22, 21, 14, 17, 18, 10, 15, 19, 13, 11, 23, 12, 26, 24, 25, ...
这是我正在排序的 100 个元素中的前 27 个元素。这就是我填写随机列表的方式:
for(int i =0; i < 100; i ++){
int nr = rand.nextInt(100);
if (!numbers.contains(new Integer(nr))){
numbers.add(nr);
}else {
i--;
}
}
这是快速排序的代码:
public class Quicksort{
@SuppressWarnings("unchecked")
static public <T> ArrayList<T> sortting(ArrayList<T> t){
//System.out.print("-");
T piv;
ArrayList<T> left ,right ,newT;
left = new ArrayList<T>();
right = new ArrayList<T>();
newT = new ArrayList<T>();
if (!t.isEmpty()){
piv = t.get(t.size()/2);
for (int i =0; i < t.size(); i++){
if (0 < ((Comparable<T>) piv).compareTo(t.get(i))){ //left
left.add(t.get(i));
}else{ //right
right.add(t.get(i));
}
}
if (left.isEmpty() || right.isEmpty()){
newT.addAll(left);
newT.addAll(right);
return newT;
}else {
right = sortting(right);
left = sortting(left);
newT.addAll(left);
newT.addAll(right);
}
return newT;
}
return null;
}
}