Search code examples
javaswap

why my swap is not working in cyclic sort?


     int temp=arr[i];
     arr[i]=arr[arr[i]-1];
     arr[arr[i]-1]=temp;
   

This Swap part of the code is not working correctly. i have written same swap code for other sorting algorithms, but I am facing issue with this. Also anyone can please give me clarity on pass by value of java.


Solution

  • arr[i]=arr[arr[i]-1];
    arr[arr[i]-1]=temp;
    

    This doesn't work as a swap because arr[i] changes on the first line, so it points to a different index.

    Instead, you probably want

    arr[i] = arr[temp - 1];
    arr[temp - 1] = temp;
    

    ...since you already have arr[i] stored in a convenient variable.