Following it the code for selection sort and when I try to swap the minimum element with bigger one it doesn't work using XOR operator.It displays 0 in place of values.But swap is working on two constant integers.Why?
import java.io.*;
class selection {
public static void main(String s[])throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter n");
int n=Integer.parseInt(br.readLine());
System.out.println("Enter array");
int a[]=new int[n];
for(int i=0;i<n;++i) {
a[i]=Integer.parseInt(br.readLine());
}
int min;
System.out.println("Entered Array : ");
for(int i=0;i<n;++i)
System.out.print(a[i]+" ");
for(int i=0;i<n;++i) {
min=i;
for(int j=i+1;j<n;++j) {
if(a[min]>a[j])
min=j;
}
a[min]=a[min]^a[i];
a[i]=a[min]^a[i];
a[min]=a[min]^a[i];
}
System.out.println("\nSorted Array : ");
for(int i=0;i<n;++i) {
System.out.print(a[i]+" ");
}
}
}
OUTPUT is :
Enter n
8
Enter array
1
5
4
6
2
8
9
7
Entered Array :
1 5 4 6 2 8 9 7
Sorted Array :
0 2 0 5 0 7 8 0
Swapping elements with XOR will not work if the elements are equal and this is explicitly pointed out in most books. What happens here is the following - if the i-th element is the minimal on the i-th iteration you will try to swap it with itself which causes its value to become 0.
In order to avoid this problem, before swapping numbers using XOR check if thier values are equal. In your case if you are sure the array does not contain equal elements simply do not swap if min==i
.