Question: You are given a sorted array containing both negative and positive values. Resort the array taking absolute value of negative numbers. Your complexity should be O(n)
Ex. A = {-8,-5,-3,-1,3,6,9} Expected Output: {-1,-3,3,-5,6,-8,9}
Ex. A = {-8,-5,-3,-1,3,6,9} Expected Output: {-1,-3,3,-5,6,-8,9}
package nagarro; public class SortAbsolute { public static void main(String[] args) { int array[] = { -8, -5, -3, -1, 3, 6, -9 }; printnlogn(array);// complexity O(nlogn) uses insertion sort printn(array);// complexity O(n) uses counting sort } static public void printn(int arr[]) { int max = 0;// absolute max int b[] = new int[arr.length]; for (int a : arr) { if (max * max < a * a) max = a; } if (max <= 0) max = -max; // System.out.println("max " + max); int c[] = new int[max + 1]; for (int a : arr) { if (a >= 0) c[a] = c[a] + 1; else c[-a] = c[-a] + 1; } // step 1 over /*for (int i : c) System.out.print(i + ","); System.out.println(" --");*/ for (int i = 1; i < max + 1; i++) c[i] = c[i - 1] + c[i]; // step 2 over /*for (int i : c) System.out.print(i + ","); System.out.println(" --");*/ for (int i = arr.length - 1; i >= 0; i--) { if (arr[i] >= 0) { b[c[arr[i]] - 1] = arr[i]; c[arr[i]]--; } else { b[c[-arr[i]] - 1] = arr[i]; c[-arr[i]]--; } } for (int i : b) System.out.print(i + ","); System.out.println("-- complexity O(n)"); } static public void printnlogn(int arr[]) { int j = 0; int temp; for (int i = 1; i < arr.length; i++) { j = i - 1; temp = arr[i]; while (j >= 0 && compare(arr[j], temp)) { arr[j + 1] = arr[j]; arr[j] = temp; j--; } } for (int a : arr) System.out.print(a+","); System.out.println("-- complexity O(nlogn)"); } static public boolean compare(int a, int b) { a *= a; b *= b; if (a > b) return true; return false; } } OUTPUT
-1,-3,3,-5,6,-8,-9,-- complexity O(nlogn) -1,-3,3,-5,6,-8,-9,-- complexity O(n)