'What is the role of the temp integer in the bubble sort code
int[] array = {4, 5, 7, 6, 9, 10,67,6,45};
for (int i = 0; i < array.length; i++) {
for (int j = i+1; j < array.length; j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
Just wondering what is the role of array[j] = temp;
This is the bubble sort sorting algorithm, new to Stack exchange so formatting might not be great
Solution 1:[1]
Imagine that you have a red ball in your left hand, and a blue ball your right.
Now switch the balls ... without throwing them in the air.
How? Let me lend you a hand!
Explanation: 1) You need 3 hands to do this ... and by analogy, 3 variables. 2) "To lend a hand" means "to help"
Solution 2:[2]
There is a trick to do this without an additional variable, using XOR:
array[i] ^= array[j];
array[j] ^= array[i];
array[i] ^= array[j];
However:
- This is pretty opaque to anybody who hasn't seen this trick before, or who doesn't understand how xor-ing works
- This only works for types you can XOR. For example, you can't swap objects like this.
Using a temporary variable, as explained in other answers, is a well-known, simple way to express swapping.
Another way to think of it: two cars trying to get past each other on a narrow road:
Parking space
|
Car1 > -----/-\----- < Car2
To get past each other, Car1
can drive into the parking space:
Car1
|
-----/-\----- < Car2
Car2
can drive on:
Car1
|
Car2 < -----/-\-----
Then Car1
can drive on:
|
Car2 < -----/-\----- > Car1
The temporary variable is the "parking space".
Solution 3:[3]
The temp
variable is used for switching between array[i]
and array[j]
- you save array[i]
to a temporary location, overwrite it with array[j]
, and then assign the value you set aside (in temp
) to array[j]
.
Solution 4:[4]
The role of temp
is to temporarily hold the value.
int temp = array[i];
array[i] = array[j];
array[j] = temp;
This type of primitive value can only hold one value at a time.
Imagine you and a friend are holding a very heavy object each, and you can only hold one of them. If you want to swap objects with a friend, you will have to put your object somewhere first before getting the object from your friend. After he has given it to you, then the friend can then pick up the other object.
Solution 5:[5]
In addition to @Andy Turner 's answer you could avoid temp variable and not even use xor:
array[i] = array[i] + array[j];
array[j] = array[i] - arra[j];
array[i] = array[i] - array[j];
But as you can see (and as other answers explained) using temp is more clear,readable and easy to understand. That's why most tutorials use temp variable in order to be easy to understand and learn the algorithm.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | Mureinik |
Solution 4 | |
Solution 5 | coder |