15. Getting Technical - How does it work?



My code works. I do not understand it. Neither line beginning "books.sort!" makes sense to me. Could someone please walk me through what is actually happening? ty!

books = ["Charlie and the Chocolate Factory", "War and Peace", "Utopia", "A Brief History of Time", "A Wrinkle in Time"]

# To sort our books in ascending order, in-place
books.sort! { |firstBook, secondBook| firstBook <=> secondBook }

# Sort your books in descending order, in-place below

books.sort! { |firstBook, secondBook| secondBook <=> firstBook }


The Array#sort! method takes a block consisting of two block parameters and a two-way comparison operation. When the comparison operands are in the same order as the block parameters, the sort is from lowest to highest (ascending order). When they are opposite, the order is reversed.

The way the two-way comparison works is like an if..elsif..else statement.

Given a and b,

if a < b
    return -1
elsif a > b
    return 1
    return 0

For an aascending sort, when the comparison returns 1, the two operands are swapped.

I cannot say with exact certainty but this looks to be a Merge Sort algorithm.


Sorry, I am really struggling with this.

I see how what I posted matches your "if else".
I see that sort! on it's own just sorts the array and saves it back to the array.
I do not see how returning a -1, 0, or 1 tells the array what order to sort things in.


It's happening internally over several iterations. Consider a basic merge sort (I hope I get this right, but I gave you link to read up on for confirmation).

v, r, z, a, t, b, p, q, l, g, y, k

Now splitting into pairs and sorting in ascending order...

r, v, a, z, b, t, p, q, g, l, k, y

r, a, v, b, z, p, t, g, q, k, l, y

a, r, b, v, p, z, g, t, k, q, l, y

a, b, r, p, v, g, z, k, t, l, q, y

a, b, p, r, g, v, k, z, l, t, q, y

a, b, p, g, r, k, v, l, z, q, t, y

a, b, g, p, k, r, l, v, q, z, t, y

a, b, g, k, p, l, r, q, v, t, z, y

a, b, g, k, l, p, q, r, t, v, y, z

The -1, 0, 1 don't tell the order to sort, just whether to swap the pair or not.


Thank you so much for taking the time to explain this! Awesome! I feel like I have a much better handle on it. (And I didn't realize Merge Sort was a link before but now I am reading it.)



I don't think I got the algo correct but you get the picture, right?


Yeah, your explanations on the second post are what clicked for me.

"It's happening internally over several iterations." and "The -1, 0, 1 don't tell the order to sort, just whether to swap the pair or not."



2 posts were split to a new topic: Why doesn't books.sort!.reverse work?