Beauty or Horror?

August 2, 2006 at 11:43 am

Here, take a look at this.

List quickSort(List list) {
    if(list == null || [list count] == 0)
        return list;

    id x = [list first];
    List tail = [list tail];

    List ltx = [tail filter:lambda (id y) -> y < x];
    List gtex = [tail filter:lambda (id y) -> y >= x];
    return [[quickSort(ltx) addObject: x] addList: quickSort(gtex)];
}

The first line of the function is a base case check. It returns list if it is either null or empty.

Next, we create two local variables. One, called x, holds the first element of list, the other, called tail, is a List of all elements of list, sans the first element.

Then, we create two new Lists. The first is a List of all elements of tail that have a value less than x, and the second is a List of all elements of tail that have a value greater than or equal to x.

Finally, we return a new List created by merging the two Lists and x together.