The algorithm to swap the values of two integers x
and y
without using a tmp
variable is
x = x + y;
y = x - y;
x = x - y;
I've written a code to sort an array by passing it to a method. The method accepts the array in a pointer *ptr
. Thus, the elements of the array, arr[0], arr[1],...
would be accessed with the pointer variable as *(ptr + 0), *(ptr + 1),...
. However, the problem I'm facing is that when I try to swap the values of the array while sorting by referencing the memory location with a pointer, without the use of a temporary variable, the array is not getting sorted the way I expect and, instead, I see some random elements getting inserted into the array.
This is my array sorting code (selection sort - the sort algorithm is correct):
void sort(int *arr, int n){
int i,j,m;
for(i=0; i<n-1; i++){
m = i;
for(j=i+1; j<n; j++){
if(arr[j] < arr[m])
m = j;
}
//swapping arr[i] and arr[m]
*(arr + i) = *(arr + i) + *(arr + m);
*(arr + m) = *(arr + i) - *(arr + m);
*(arr + i) = *(arr + i) - *(arr + m);
}
//print the array...
}
void main(){
int arr[] = {2,4,3,5,8,7};
sort(arr, 6);
}
INPUT:
2 4 3 5 8 7
EXPECTED OUTPUT:
2 3 4 5 7 8
OBTAINED OUTPUT:
0 3 0 0 7 8
Why is this happening? What am I doing wrong?