This is a Ruby language question.
The sources are as follows:
x=["abc", "dejgk", "loqp" ]
px.sort {|a,b|a<=>b}#1 Processing
px.sort {|a,b|b<=>a}#2 Processing
# ["abc", "dejgk", "loqp"]
# ["loqp", "dejgk", "abc"]
How does the sort method work with the <=> operator evaluation?
The process I am thinking about is as follows, but it does not match the execution results and
I don't know what to do correctly.
処理 Processing
"abc" <=> "deigk" Assessment-1 "abc" stored in array [0].Store "deigk" in array [1]
Store "deigk" <=> "loqp" Assessment-1 "deigk" in array (1).Stored "loqp" in array [2].
# ["abc", "dejgk", "loqp"]
処理 Processing
"deigk" <=> "abc" Assessment 1 "abc" stored in array [1].Stored "deigk" in array [0].
Store "loqp" <=>"abc" Assessment 1"abc" in array [2].Stored "loqp" in array [1].
#["deigk", "loqp", "abc"]
As this is the first time I have posted a question, I would appreciate it if you could do something.
That's all.
Thank you for your cooperation.
Array#sort
rearranges elements of an array according to the evaluation rules specified in the block.
Comparisons are not always made sequentially from the beginning of the array.In this example, when I tried it on hand, the comparisons were made in the following order:
<"dejgk"<=>"loqp"
,"abc"<=>"dejgk"
② "dejgk"<=>"loqp"
, "abc"<=>"loqp"
, "abc"<=>"dejgk"
Users don't usually need to know the sort algorithm inside the sort method.
I think the sort algorithm used in Array#sort
is called quick sort.
© 2024 OneMinuteCode. All rights reserved.