|
| 1 | +/*Copyright (c) Jul 2, 2015 CareerMonk Publications and others. |
| 2 | + * E-Mail : info@careermonk.com |
| 3 | + * Creation Date : 2015-01-10 06:15:46 |
| 4 | + * Last modification : 2006-05-31 |
| 5 | + by : Narasimha Karumanchi |
| 6 | + * File Name : ConvertArraytoSawToothWave.java |
| 7 | + * Book Title : Data Structures And Algorithms Made In Java |
| 8 | + * Warranty : This software is provided "as is" without any |
| 9 | + * warranty; without even the implied warranty of |
| 10 | + * merchantability or fitness for a particular purpose. |
| 11 | + * |
| 12 | + */ |
| 13 | + |
| 14 | +package chapter10sorting; |
| 15 | + |
| 16 | +class SortedSquaredArray { |
| 17 | + public int[] sortedSquaredArray(int[] A) { |
| 18 | + int n = A.length; |
| 19 | + int j = 0; |
| 20 | + // Find the last index of the negative numbers |
| 21 | + while (j < n && A[j] < 0) |
| 22 | + j++; |
| 23 | + // i points to the last index of negative numbers |
| 24 | + int i = j-1; |
| 25 | + |
| 26 | + int[] result = new int[n]; |
| 27 | + int t = 0; |
| 28 | + // j points to the first index of the positive numbers |
| 29 | + while (i >= 0 && j < n) { |
| 30 | + if (A[i] * A[i] < A[j] * A[j]) { |
| 31 | + result[t++] = A[i] * A[i]; |
| 32 | + i--; |
| 33 | + } else { |
| 34 | + result[t++] = A[j] * A[j]; |
| 35 | + j++; |
| 36 | + } |
| 37 | + } |
| 38 | + // add the remaining negative numbers squares to result |
| 39 | + while (i >= 0) { |
| 40 | + result[t++] = A[i] * A[i]; |
| 41 | + i--; |
| 42 | + } |
| 43 | + |
| 44 | + // add the remaining positive numbers squares to result |
| 45 | + while (j < n) { |
| 46 | + result[t++] = A[j] * A[j]; |
| 47 | + j++; |
| 48 | + } |
| 49 | + |
| 50 | + return result; |
| 51 | + } |
| 52 | +} |
0 commit comments