Monday, December 31, 2018

Sorting an array using single loop



 

            package example;

public class singleLoopSort {

public static void main(String[] args) {
int[] list = {23,90,45,78,56,45,23};
int temp;

for(int i = 0; i < list.length - 1; i++)
{
if (list[i] > list[i + 1]) {
temp = list[i];
list[i] = list[i + 1];
list[i + 1] = temp;
i = 0;
}
}

  for (int i = 0; i < list.length; i++) {
        System.out.print(list[i] + " ");
    }
 
  System.out.println("REVERSE ORDER :");
  for (int i = list.length -1 ; i >= 0; i--) {
        System.out.print(list[i] + " ");
    }  
}

}

output:
23 45 56 78 90
REVERSE ORDER : 90 78 56 45 23 

No comments:

Post a Comment