package arrays; public class Arrays { public static void main(String[] args) { // TODO code application logic here int[] ar = {12,-3,8,1,19,22,0}; int temp; for(int i = 0; i<ar.length-1;i++) { if(ar[i]>ar[i+1]) { temp=ar[i+1]; ar[i+1]=ar[i]; ar[i]=temp; } } //НЕ ПОЛУЧАЕТСЯ ВЫВЕСТИ ЧИСЛА В ОТСОРТИРОВАННОМ ПОРЯДКЕ } for(int i=0; i<ar.length; i++) { System.out.println(ar[i]); } } 

Closed due to the fact that it was off topic by Nicolas Chabanovsky 15 May '17 at 6:48 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • “Questions asking for help with debugging (“ why does this code not work? ”) Should include the desired behavior, a specific problem or error, and a minimum code for playing it right in the question . Questions without an explicit description of the problem are useless for other visitors. See How to create minimal, self-sufficient and reproducible example . " - Nicolas Chabanovsky
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • Write what is going wrong. Otherwise, it is not clear what error is meant. - default locale
  • Can not display numbers in sorted order - Ramil Aliyev
  • Currently the code is not compiled. Read how to create a MSVP - default locale

1 answer 1

You go through one cycle, swapping adjacent elements. Put a flag and execute a cycle until, having passed through it, I swap elements.

 public static void main(String args[]) { int[] ar = {12,-3,8,1,19,22,0}; int temp; boolean flag = true; while (flag) { flag = false; for(int i = 0; i<ar.length-1;i++){ if(ar[i]>ar[i+1]){ temp=ar[i+1]; ar[i+1]=ar[i]; ar[i]=temp; flag = true; } } } for(int i = 0; i<ar.length;i++){ System.out.print(ar[i] + " "); } } 

I suggest that you try to implement a bubble sort algorithm. If so, then it should look something like this.

 public static void main(String args[]) { int[] ar = {12,-3,8,1,19,22,0}; int temp; for(int i = 0; i < ar.length; i++){ for (int j = 1; j < (ar.length - i); j++) { if(ar[j - 1] > ar[j]){ temp=ar[j-1]; ar[j-1]=ar[j]; ar[j]=temp; } } } for(int i = 0; i<ar.length;i++){ System.out.print(ar[i] + " "); } } 
  • Thanks a - Ramil Aliyev
  • Of course, knowledge of sorting algorithms is good, but in practice it is better not to reinvent the wheel, but to use Arrays.sort() or Collections.sort() for collections :) - SlandShow