4 ms·
Writing quicksort non-functionally doesn't HAVE to be unreadable. Not that I disagree with Haskell being great and all, I just think it's important to realize t
by keeg 12y ago
Writing quicksort non-functionally doesn't HAVE to be unreadable. Not that I disagree with Haskell being great and all, I just think it's important to realize that imperative != ugly code.
public class QS {
public List<T> Quicksort<T>(List<T> l, Comparator<T> comp) {
if (l.size() <= 1) {
return l;
}
List<T> lesser = new ArrayList<T>();
List<T> greater = new ArrayList<T>();
T pivot = l.get(0);
for (T t: l) {
if (comp.compare(pivot, t) <= 0) {
lesser.add(t);
} else {
greater.add(t);
}
}
List<T> out = new ArrayList<T>();
out.addAll(Quicksort(lesser));
out.addAll(Quicksort(greater));
return out;
}
}
- deleted 12y ago[deleted]
- senorprogrammer 12y agoI think you just described programming.
- peteratt 12y agoAgree. Should rephrase it: by having higher-level abstractions and decoupling state from logic functional languages make it harder to make mistakes and write bad code. At least that's what I've discovered when applying its "way of thinking" to my own work.
- tromp 12y agoThis will recurse forever when sorting the list [1,0]. Which is why you need to take out the pivot to ensure that the lists you recurse on get smaller and smaller...