15. Getting Technical - How does it work?


#1



https://www.codecademy.com/en/courses/ruby-beginner-en-ET4bU/3/4?curriculum_id=5059f8619189a5000201fbcb#


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 }


#2

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
else
    return 0
end

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.


#3

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.


#4

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.


#5

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.)

:slight_smile::grinning::relaxed:


#6

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


#7

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."

:smiley:


#8

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


#10