[FIXED] why my swap is not working in cyclic sort?

Issue

     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.

Answered By – Louis Wasserman

Answer Checked By – Dawn Plyler (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published