+ 1

Guys Another problem :)

I don't think that there is any problem in logic i have checked it and dried run it couple of times. still not getting the desired output. Can anyone find the problem? Attempt is here 👇 https://code.sololearn.com/cDkQ2px2oNVx/?ref=app output will be //output = 1,1,2,2,3,3,5,8

8th Sep 2022, 1:22 PM
Davinder Kumar
Davinder Kumar - avatar
5 Answers
+ 5
if(arr[i]!=arr[arr[i]-1]) what are you trying by this statement? When i = 0, arr[ 0 ] != arr[ arr[0] - 1 ] 2 != arr[1] => 2 != 3 when you try to swap, 2 by 3 : int temp=arr[i]; // 2 arr[i]=arr[arr[i]-1]; 2 replaced by arr[ 2-1] = 3 But next arr[ 0 ] is 3 so arr[ 3-1] = 1 is replaced by 2 by arr[arr[i]-1]=temp; So array is 3,3,2,8,2,3,5,1 You are changing entire array.. By this you need 2 temp variables.. But why are you comparing arr[ I] != arr[ arr[ I ] -1 ] to swap? What is your expected output? And you may have infinite loop once id condition is true....
8th Sep 2022, 4:10 PM
Jayakrishna 🇼🇳
+ 2
Your sorting algorithm seems incorrect. either you can use builtin Arrays.sort() or learn again : https://www.geeksforgeeks.org/sorting-algorithms/ import java.util.Arrays; public class Program { public static void print(int arr[]){ for(int i=0;i<arr.length;i++){ System.out.print(arr[i]); if(i<arr.length-1) System.out.print(","); } } public static void main(String[] args) { int arr[]={2,3,1,8,2,3,5,1}; Arrays.sort(arr); //output = 1,1,2,2,3,3,5,8 print(arr); } }
8th Sep 2022, 1:44 PM
Prashanth Kumar
Prashanth Kumar - avatar
+ 2
Sry it still don't work. You are modying arr[i] by arr[i]=tempy; So next one arr[ arr[i] ] will point to some other new location, not the previous one before change in arr[arr[i]-1]=tempy; and tempy = temp will not affect arr elements at any location. edit: can you explain about your logic?
8th Sep 2022, 9:23 PM
Jayakrishna 🇼🇳
+ 1
i don't want to use other approach i know other many approaches but this is "swap sort" approach which i am learning. we don't need to use extra space and can complete operation with O(1).
8th Sep 2022, 1:59 PM
Davinder Kumar
Davinder Kumar - avatar
+ 1
I made extra temp variable to store //arr[arr[i]-1]
8th Sep 2022, 5:57 PM
Davinder Kumar
Davinder Kumar - avatar