// сортируем for(int i = 0 ; i < arr.length-1 ; i++){ boolean swapped = false; for(int j = arr.length-1 ; j > i ; j--){ if( arr[j] > arr[j+1] ){ int tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp; swapped = true; } } if(!swapped) break; } 
  • What is the question? - pavel
  • what is wrong? not working - Man
  • I finally decided it)))) - Man

2 answers 2

Well, if you briefly need to replace the line

 for(int j = arr.length-1 ; j > i ; j--) 

on

 for(int j = arr.length-2 ; j >= 0 ; j--) 

If you do not do this, then there will be an IndexOfBoundException exception or something like that, because we take the element j+1 , i.e. at the beginning of the cycle j+1 = arr.length and there is no such element.

In the bubble implementation there will be this condition >= 0 , you are probably confused with another sorting. (Otherwise it just incorrectly sorts).

You could also use the debugger and see the program behavior step by step.

  • debugger is how? - Man
  • 2
    @Petya Petrosyan, if you write code in any development environment, you can execute it step by step, usually the f7 / f8 / f4 keys and setting the breakpoint (breakpoint) by line number (or somewhere nearby). More details need to look in the settings of a specific environment. - pavel
  • I correctly understood that in Wikipedia, a boolean type was used to solve the issue with a single array, or why is it needed? - Man
  • @ Petya Petrosyan did not understand the question, throw a link to the article or explain what a single array is. - pavel
 // сортируем for(int i = 0 ; i < arr.length-1 ; i++){ boolean swapped = false; for(int j = arr.length-2 ; j >=i ; j--){ if( arr[j] > arr[j+1] ){ int tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp; swapped = true; } } if(!swapped) break; }