quicksort explained

Slowsort >_<

How it works:

Given an array [7, 2, 5, 1, 8, 3]

Have one pointer pointing to the lowest index of the array and another pointer pointing to the highest index of the array.

Lets call the low pointer L and high pointer H.

[7, 2, 5, 1, 8, 3]
 L              R

Choose a randon index and make the value of that index the pivot.

I’ll choose the first index as the pivot.

 P
[7, 2, 5, 1, 8, 3]
 L              R

Now L will increment (move right) until it finds a value >= P.

So while arr[L] < P move right, then stop when it reaches a value >= P.

 P
[7, 2, 5, 1, 8, 3]
 L              R

Here P = 7 and arr[7] = 7, so we stop moving L.

Now H will decrement (move left) until it finds a value <= P.

So while arr[H] > P move left, then stop when it reaches a value <= P.

 P
[7, 2, 5, 1, 8, 3]
 L              R

Here P = 7 and arr[H] = 3, so we stop moving P.

If L < H (the index of L and H not the values) then you swap arr[L] and arr[H] (swap the values at L and H).

 P
[3, 2, 5, 1, 8, 7]
 L              R

Now repeat.

 P
[3, 2, 5, 1, 8, 7]
    L           R

Here P = 3 and arr[L] = 2, 2 is not >= 3 so we increment L.

 P
[3, 2, 5, 1, 8, 7]
       L        R

Here P = 5 and arr[

Tags: