From: "Haris Bogdanoviæ" Date: 2009-07-12T22:25:05+09:00 Subject: Re: one line sorting It turns out that I was right about having different number of exchanges but I was wrong about direction. If you sort numbers from lowest to biggest you need smaller number of exchanges than if you sort in opposite direction. I made a test and in this particullar list [7,4,9,55,98,11,42] it's 11 exchanges for smallest to biggest number and 18 for biggest to smallest.. "Haris Bogdanovi�" wrote in message news:h3ciqh$rv8$1@gregory.bnet.hr... > >The bubblesort you did here will not be faster, no matter what order >>you traverse the items in. After all, you will look at each item in the >>outer loop and again at each item in the inner loop again. >>That makes it n-squared no matter what order you traverse them in. > > Just think. If you go from biggest to smallest in inner loop then > if you put smaller number at the beginning then bigger number > goes somewhere in the list. If you find even smaller number then exchange > repeats but the two numbers you exchanged are in better place, the smaller > number > stands before bigger. > That means that there will be less exchanges needed if you traverse inner > loop > from last to first. Reversing elements will not help. > So it's true that there will be same number of times going through loops > but > there will be less exchanges needed so that is why it would be faster. > >>[1,2,3,4].reverse.each_with_index > > As I said that will not help. > But there is a way to get that speed increment. > The list has to be sorted from biggest to smallest and then do reverse, > but then, reverse takes some time. > >