質問

I have the following code that bubble sorts the array parameter.

   def bubble_sort(arr)
      sorted = false
      until sorted
        sorted = true
        (arr.count - 1).times do |i|
          if arr[i] > arr[i + 1]
            arr[i], arr[i + 1] = arr[i + 1], arr[i]
            sorted = false
          end
        end
      end

      arr
    end

I want to understand specifically this line: arr[i], arr[i + 1] = arr[i + 1], arr[i]

say in this case arr[i] = 1 and arr[i+1] = 3

The expression would be in all intents and purposes 1, 3 = 3, 1

Obviously that would give me an error, so I'm assuming this works only when valued are assigned to variables.

However, it still seems counter-intuitive to me. I would expect the code: arr[i], arr[i + 1] = arr[i + 1], arr[i] to give me an error. Is there anyone that can help me reason why this is a valid expression?

役に立ちましたか?

解決

All it's doing is swapping two entries in an array.

arr[i] is being set to the current value of arr[i+1] and at the same time arr[i+1] is being set to the current value of arr[i]. It's called multiple assignment or parallel assignment.

So to take your example:

say in this case arr[i] = 1 and arr[i+1] = 3

It's doing arr[i] = 3 and arr[i+1] = 1 at the same time so the values in the array end up swapped.

You could do it in separate statements but you would need to use some temporary variable to hold one of the values otherwise the two values in the array would end up equal. e.g.

temp_value = arr[i]
arr[i]     = arr[i+1]
arr[i+1]   = temp_value

他のヒント

Look for the if statement. In order to swap two values, the if condition should be satisfied.In your example swapping does not occur since (arr[i] = 1) > (arr[i + 1] = 3) is false. In this case the values will keep their position.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top