I am trying a simple insertion sort. But the swapping I am trying isn’t working when I use bit-wise operation.
But when I use another temporary variable the swapping works. When I compile this code I always get some extra 0s.
How can I figure out what is wrong with my code?
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<algorithm>
using namespace std;
void swap(int* a, int* b)
{
*a=*a^*b;
*b=*a^*b;
*a=*a^*b;
}
int main(void)
{
int arr[size];
int i,j,min;
for(i=0; i<size; i++)
arr[i]=rand()%100;
for(i=0; i<size; i++)
printf("%d ",arr[i]);
putchar('\n');
for(i=0; i<size;i++)
{
min=i;
for(j=i+1;j<size;j++)
if(arr[j]<arr[min])
min=j;
swap(&arr[i],&arr[min]);
}
for(i=0; i<size; i++)
printf("%d ",arr[i]);
putchar('\n');
return 0;
}
In
if
arr[i]is the smallest array element, you try to swap it with itself, so the two pointers you pass to swap point to the same memory location, hence the xor zeros out that location.