
Quicksort in Swift - fjcaetano
https://gist.github.com/fjcaetano/b0c00a889dc2a17efad9
======
gilgoomesh
If anyone's wondering, yes, there's a quickSort function already in the Swift
standard library (no import required):

    
    
        var ar = [3456,45,53567,356,7225,47858]
    
        quickSort(&ar, Range(start: ar.startIndex, end: ar.endIndex))
    
        // [45, 356, 3456, 7225, 47858, 53567]
    

There's also a version that let's you specify the "less" comparator.

~~~
jkubicek
How did you discover this?

~~~
gilgoomesh
Use a Swift standard library function in the documentation (like println).
Command-Click on it to go to it's definition. You're taken to a header-like
description of the standard library (assuming the index has been built for
your project – sometimes you have to wait a few minutes in a new project).

------
dstaley
I was surprised this example didn't take advantage of Swift's built-in
Comparable protocol, so I rewrote it! I also wrote an example of how you can
implement the Comparable protocol for a struct, so that they can then be
sorted.

[https://gist.github.com/dstaley/e7171375d3f5cb9f2fe4](https://gist.github.com/dstaley/e7171375d3f5cb9f2fe4)

------
shawkinaw
This actually highlights one area where I find Swift slightly deficient. I was
just thinking earlier today that Swift is remarkably close to my dream
language, i.e. incorporates the great features of many languages I've come in
contact with. But one thing it lacks is Haskell's amazing list comprehension,
which helps make Haskell quicksort so succinct.

~~~
alayne
That quicksort one-liner that you often see for Haskell is crap.

------
djb_hackernews
Had a chat about Swift over lunch today, one topic was the choice of using ..
and ... to represent ranges. Interesting to see the comments of the gist focus
on this as well. Surely is a confusing and potentially dangerous syntax.

~~~
gilgoomesh
Interestingly, the .. and ... operators are not part of the language but are
defined in the standard library.

This means you can override .. (to disable it) and define your own operator
for half-closed ranges if you'd prefer (Swift supports building your own
operators from combinations of punctuation characters). At least I think you
could do this: I haven't tried.

~~~
Someone
If so, that opens entire new routes for obfuscation.

For the subject at hand: I would like to have seen ranges use () for open
endings and [] for closed ones. For example, [1..5) would include 1 but
exclude (that is standard notation in mathematics. See
[http://en.wikipedia.org/wiki/Interval_(mathematics)#Excludin...](http://en.wikipedia.org/wiki/Interval_\(mathematics\)#Excluding_the_endpoints))

Back to the obfuscation thing: unfortunately for that goal, one cannot create
prefix operators with names (, [ or {

It _is_ possible to define an infix operator named ., though. That could give
whole new meaning to what look like floating point values such as 3.14.

------
brudgers
Hoare's original paper from 1962.

[http://comjnl.oxfordjournals.org/content/5/1/10.full.pdf+htm...](http://comjnl.oxfordjournals.org/content/5/1/10.full.pdf+html)

There are reasons not to perform quickSort the way people did fifty years ago.
Data sets are larger and worst case time for quickSort approach 0(n^2) when
data is already ordered and pivots are selected in-order. Randomizing pivot
selection mitigates this back toward O(log n).

All that mutation and pointer swapping are artifacts of the way things used to
have to be done by programmers. And they're useful as academic exercises.
Hoare's algorithm is really fucking brilliant. But mapping and filtering in a
functional style, makes more sense than dotting the 'i's and 'j's if someone
is going to be reading and maintaining the code. There's a reason people don't
use C to program mobile devices.

Moreover, while Hoare's original algorithm was designed to work in place, the
idea of working in place is less coherent today. When we strive to distribute
and parallelize big nasty resource intensive jobs, what does "in-place" mean?
See Leslie Lamport, _Thinking for Programmers_ at about time = 36:00

[http://channel9.msdn.com/Events/Build/2014/3-642](http://channel9.msdn.com/Events/Build/2014/3-642)

And even on a non-distributed system, when are we really coming up against the
bounds of 'fast memory' these days? A serious problem that stretches 16
GigaBytes of RAM is less than $10,000 from 64 GigaBytes...or $200 from an SSD
and using 'slow memory'.

Of course if we are parallelizing, we can even do it on one machine and again,
what is 'in-place'? The caches? Again which ones and at what level. The Swift
code (or Java or C#) may look like C, but it's not. It may be garbage
collected, JIT'd, byte coded, and micro-coded all before it hits the mulit-
stage branch predicting pipeline from several levels of cache reading from
code pages that may have gone in and out to disk as threads and tasks switch.

'Place' might just mean somewhere. But probably somewheres.

------
imkevinxu
I can't wait until GitHub or someone adds in Swift syntax highlighting

------
alayne
What kind of monster writes i += 1?

~~~
neurobro
I do, only because I've never seen a convincing case where unary
increment/decrement improves the code in any way (and I've searched).

~~~
nkeets
So, what convincing cases have you find of i += 1 over i = i + 1?

~~~
exogen
Consider a more descriptive variable name and hopefully it becomes obvious:

    
    
        sheepCounted += 1
    

vs.

    
    
        sheepCounted = sheepCounted + 1

~~~
Someone
It can easily get way worse once you consider classes and their properties:

    
    
        pInterface->m_someField[currentItem] += 1;

------
supersillyus
From that, it's not too hard how people could think it was influenced by Go
(though it apparently wasn't):
[http://play.golang.org/p/oWNRd0D2Zp](http://play.golang.org/p/oWNRd0D2Zp)
looks superficially very similar

------
nextstep
I like the syntax of Swift

~~~
Alupis
Looks like a bizarre mix of JavaScript and C to me.

But then, hey... Objective-C syntax just offends me right-out ;-P

------
kiwiwearables
was waiting for someone to put this out :) awesome.

------
hadoukenio
Until Apple open Swift, I'm sorry, it's DOA.

~~~
melling
I'm sorry but that's silly. While I really hope that Swift does become a
cross-platform language, it's pretty safe to assume that it will become the
defacto Apple development language. It offers way too much in terms of
developer productivity.

------
seanewest
I put your code on npm:
[https://www.npmjs.org/package/quicksort.swift](https://www.npmjs.org/package/quicksort.swift)

Edit: ...and then swiftly unpublished. It is unclear to me the legal issues
involved in forking and publishing unlicensed gists.

[http://stackoverflow.com/questions/4007674/whats-the-
default...](http://stackoverflow.com/questions/4007674/whats-the-default-
license-of-code-published-at-github)

~~~
arrakeen
why would you publish that on npm? i'm not familiar with the ecosystem, is
there a precedent for publishing non-js source files on npm?

~~~
seanewest
There is precedence for publishing non-js code on npm:
[https://github.com/substack/dotc](https://github.com/substack/dotc)

~~~
Jtsummers
That looks to be JS code that implements a C preprocessor. And the C code
present in it seems to be for demonstrating/testing the preprocessor.

~~~
seanewest
Scroll down to the section "publishing c modules". It advocates publishing
dotc modules on npm.

"npm? Isn't that for javascript?

Yes, but:

native node modules are written in c++

npm already exists

npm installs packages in a way that avoids dependency hell"

------
Alupis
Wow... seems like a nightmare for several reasons:

>Naming Constants and Variables

>You can use almost any character you like for constant and

>variable names, including Unicode characters:

>let π = 3.14159

>let 你好 = "你好世界"

>let 🐶🐮 = "dogcow"

[https://developer.apple.com/library/prerelease/ios/documenta...](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_399)

~~~
tailrecursion
I think if you're going to make a strong criticism of a complete design and
implementation that includes decisions that were almost certainly made
deliberately, then you owe an explanation or some kind of argument.

My position is that it's the language's job to allow expression of ideas and
not its job to police or disallow bad sentences. I think such a thing [EDIT:
disallowing bad sentences] is impossible and leads to COBOL-like languages.
(Compilers can have options for coding standards, like "house rules" but I
don't think it's the language's role.)

~~~
Alupis
Well, besides adding to complexity of debugging or just reading/understanding
of the codebase when the dev may not be familiar with say.. .Chinese
characters, it may also limit which platforms it can run on. But, this is an
apple language targeting only apple devices so the last part isn't much of an
issue.

Basically using unicode characters is comparable to purposeful obfuscation,
are difficult to type (no keyboard i'm aware of has a "cow" key), difficult to
read/remember, and may become wrongly converted if the code is copy/pasted
into a text editor not supporting that character.

Now, I don't think this constituted as a "strong criticism" nor warranted the
downvote nor the expletive.

