選択ソートのコードに従います。最小要素をより大きな要素と交換しようとすると、XOR 演算子を使用しても機能しません。値の代わりに 0 が表示されます。しかし、スワップは 2 つの定数整数で機能します。なぜですか?
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]+" ");
}
}
}
出力は次のとおりです。
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