class RearrangeNumber { void display(int[] arrB) { for (int i = 0; i < arrB.length; i++) { System.out.print( + arrB[i]); } } void rearrange(int[] arr){ // Indexes to store position of start and end of positive number block int startPositiveIndex=0; int endPositiveIndex=0; for(int i=0; i<arr.length; i++){ //Whenever -ve no comes, place it after last -ve no i.e. at start of //positive number block. Then shift the positive number block to right //one place if(arr[i]<0){ //change the indexes endPositiveIndex=i; //shift positive no block to right shift(arr, arr[i], startPositiveIndex, endPositiveIndex); startPositiveIndex++; //System.out.println(nst: +startPositiveIndex+tend: +endPositiveIndex); } } } private void shift(int[] arr, int noToBeMoved, int startPositiveIndex, int endPositiveIndex) { if(startPositiveIndex!=endPositiveIndex){ for(int i=endPositiveIndex; i>startPositiveIndex; i--){ arr[i]=arr[i-1]; } //place the -ve no at start arr[startPositiveIndex]=noToBeMoved; //display(arr); } } } class Final { public static void main(String args[]) { RearrangeNumber r = new RearrangeNumber(); System.out.println(nMy code result: ); int[] b ={ -1, -7, -3, 7, 5, -6, -2, -8, 9, -20, -4, 1, 3 }; System.out.println(nInput); r.display(b); r.rearrange(b); System.out.println(nRearranged output:); r.display(b); System.out.println(n); } }
©