This is a weird error that I am getting for a simple selection sort.
Use the following inputs 89,52,10,1,56,63,24,36,12,5
If you were to debug it you would notice that during the 3rd iteration the line
a[i]=a[i] ^ a[min]; sets both operand to zero.
Any Idea why this is happening ?
#include<stdio.h>
int main()
{
int a[10]={'\0'};
int i=0,j=0,k=0;
int min=0;
printf("Enter 10 Elements\n");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<10;i++)
{
min=i;
for(j=i+1;j<10;j++)
{
if(a[j]<a[min])
{
min=j;
}
}
a[i]=a[i] ^ a[min];
a[min]= a[min] ^ a[i];
a[i]= a[i] ^ a[min];
}
for(i=0;i<10;i++)
{
printf("\n %d",a[i]);
}
return(0);
}
XOR is a lousy way to swap variables. Just declare a temporary and use assignments.
The XOR trick:
fails if
xandyare the same location in memory; it will then set the value to 0.I haven’t analyzed your code in detail, but I’ll bet that this:
is failing when
i == min.…
Confirmed, I tried running the program with an added
printfstatement, and with the specified input it does the swap withi == minat least once.