13 Feb 2018

Write a Program in java to short a given array in one loop or in one iteration.

Here is a program to short a given array in one loop or in one iteration.here i a have given two methods. these are followings.

#Method-1
class SortInOneOrder {
          public static int[] insertionSort(int[] arr) {
                   for (int i = 1; i < arr.length; i++) {
                             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;
                             } 
                   }
                   return arr;
          }
          public static void main(String[] args) {
                   int[] nums = { 1, 0, 0, 0, 2, 2, 1, 1 };
                   nums = insertionSort(nums);
                   for (int n : nums)
                             System.out.print(n + ",");
          }
}
Output
0,0,0,1,1,1,2,2
#Method-2
class SortInOneOrder {
        public static void main(String[] args) {
                int arr[] = { 1, 0, 0, 0, 2, 2, 1, 1 };
                for (int i = 0, j = i + 1; i < arr.length && j < arr.length;) {
                        if (arr[i] > arr[j]) {
                                int temp = arr[i];
                                arr[i] = arr[j];
                                arr[j] = temp;
                                i = 0;
                                j = i + 1;
                        } else {
                                i++;
                                j++;
                        }
                }
                for (int n : arr)
                        System.out.print(n + ",");
                System.out.println();
        }
}
Output
0,0,0,1,1,1,2,2