What's wrong with that loop? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What's wrong with that loop?

I made a code to sort numbers because the Code that I use don't allow me to use the Sort-Methode. Code: for(int i = 0; i<input.Length -1; i++) { char c = input[i+1]; if(input [i]> input [i+1]){ input [i+1] = input [i]; input [i] = c}} Sample Input: 6875 Output: 6758 I know I could sort it better with two for loops but I would like to know why that not work.

7th Jul 2022, 3:47 PM
Felix Alcor
Felix Alcor - avatar
9 Answers
+ 1
6875 6 8 no swap=> 6875, at i th index, element is 6 8 7 swapped => 6785 , at i th, element is 8 8 5 swapped => 6758, at i th, element is 8 Continue this with 2nd loop.. 6 7 not swapped => 6758 , 7 5 swapped => 6578 7 8 no swaps => 6578 no need further swaps...
7th Jul 2022, 4:07 PM
Jayakrishna 🇮🇳
+ 1
My understanding 7>5 they shouldn't Switch and 8>7 they should also not switch why did they still do it. And why did 8 go to the beginning. I know I make it unnecresary difficult...
7th Jul 2022, 3:56 PM
Felix Alcor
Felix Alcor - avatar
+ 1
Single for loop swap only adjacent values in sorted order. You need to continue again from start until all in sorted order. See there only adjacent elements only gets compared, not any other. There may elements in different positions, not only adjacent in unsorted order. So single loop can't able to do all checks.. With single loop, in first iteration the biggest element is get placed at it right position (in the last in single iteration. So need repeating this, until all gets placed in sorted order.
7th Jul 2022, 4:02 PM
Jayakrishna 🇮🇳
+ 1
I should rly stop programming today my head already spin the values...
7th Jul 2022, 4:36 PM
Felix Alcor
Felix Alcor - avatar
+ 1
I changed now my entire code so I could use Sort because yeah I First didn't rly understand the Logic of Krapreka and... Yeah it's still seeable there. Here the Code if you want to understand for what I asked the question. 😅 https://code.sololearn.com/c1W5WyeKwY6J/?ref=app (I hate converting chars to int in c#!!!)
7th Jul 2022, 5:03 PM
Felix Alcor
Felix Alcor - avatar
+ 1
Good one. I tried this with converting to array of single digit integer.. Then applied sort..
7th Jul 2022, 5:23 PM
Jayakrishna 🇮🇳
+ 1
I'm mostly down when it comes to converting Arrays because and I had already had my Problems there with Credit Card validation... 😭
7th Jul 2022, 5:30 PM
Felix Alcor
Felix Alcor - avatar
0
It's only upto, you understand the logic.. So Just recheck.. Gets relief. Hope it helps..
7th Jul 2022, 4:41 PM
Jayakrishna 🇮🇳
0
Yeah I understand now I can just use one loop because for example with 5953 it would just loop once also 5539.
7th Jul 2022, 5:01 PM
Felix Alcor
Felix Alcor - avatar