We all have faced this question in our interview process to swap 2 variables.
If not faces while working with arrays we may have faced to swap 2 variables in array.
I hope, you all know the concept of swapping 2 variables. today I am going to show you the fastest way to swap two variables.
We all know data is stored in computer memory in the form of bits(0 & 1), that means all the operation we do on the bits will be perform faster by computer.
some bit manipulation examples :-
We will use XOR Operator to swap 2 variable :-
If not faces while working with arrays we may have faced to swap 2 variables in array.
I hope, you all know the concept of swapping 2 variables. today I am going to show you the fastest way to swap two variables.
We all know data is stored in computer memory in the form of bits(0 & 1), that means all the operation we do on the bits will be perform faster by computer.
some bit manipulation examples :-
Bitwise XOR operator :-
value ^ 0s == value
value ^ 1s == ~value
value ^ value == 0s
Bitwise AND Operator :-
value & 0s == 0s
value & 1s == value
value & value == value
Bitwise OR Operator :-
value | 0s == value
value | 1s == 1s
value | value == value
value ^ 0s == value
value ^ 1s == ~value
value ^ value == 0s
Bitwise AND Operator :-
value & 0s == 0s
value & 1s == value
value & value == value
Bitwise OR Operator :-
value | 0s == value
value | 1s == 1s
value | value == value
We will use XOR Operator to swap 2 variable :-
x = 10
y = 12
8 4 2 1
1 0 1 0 = 10(x)
1 1 0 0 = 12(y)
x = x ^ y 1010^1100 = 0110
y = x ^ y 0110^1100 = 1010 (10)
x = x ^ y 0110^1010 = 1100 (12)
We will implement a bubble sort algorithm to see the benefit of bit manipulation:-y = 12
8 4 2 1
1 0 1 0 = 10(x)
1 1 0 0 = 12(y)
x = x ^ y 1010^1100 = 0110
y = x ^ y 0110^1100 = 1010 (10)
x = x ^ y 0110^1010 = 1100 (12)
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
int[] array = new int[]{20,35,-15,7,55,1,-22};
array = bubbleSort(array);
System.out.println(Arrays.toString(array));
}
private static int[] bubbleSort(int[] array) {
for (int i=0;i<array.length;i++){
for (int j=0;j < array.length-i-1;j++) {
if (array[j] > array[j+1]){
//fastest way to swap two variable
array[j] = array[j] ^ array[j+1];
array[j+1] = array[j] ^ array [j+1];
array[j] = array[j] ^array[j+1];
}
}
}
return array;
}
}
No comments:
Post a Comment