Wednesday, July 15, 2015

Sorting the array with one loop

Hello Friends, its pretty common question in almost all the interviews that how can you sort the array with one loop, and in first thought it seems pretty difficult to understand but if you think a bit out of the box you came to know that while your loop starts (considering the Bubble sort, that takes 2 loops), you can think of resetting the outer loops variable value and thus making the loop go once again as we want to, here look what I want to say:

 public class SingleLoopSorting {  
      public static void main(String[] args) {  
           int arr[] = {  
                5, 1, 7, 3, 9  
           };  
           for (int i = 1, len=arr.length; i < len; i++) {  
                //swapping the values via a = a+b;b=a-b;a=a-b; rule, and resetting the i variable
                if (arr[i] < arr[i - 1]) { 
                     arr[i] = arr[i] + arr[i - 1];  
                     arr[i - 1] = arr[i] - arr[i - 1];  
                     arr[i] = arr[i] - arr[i - 1];  
                     i = 0;  
                }  
           }  
           System.out.print("Sorted Array : ");  
           for (int i = 0; i < arr.length; i++) {  
                System.out.print(arr[i] + " ");  
           }  
      }  
 }  

Link here

No comments:

Post a Comment