Last active
November 20, 2017 05:34
-
-
Save Ankitdet/2b5397d2e5a6460958676e9c496a46eb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package bootstrapdemo; | |
import java.util.Arrays; | |
public class RearrangeNumber { | |
public static void main(String[] args) { | |
int []array = {12,11,-3,-1,4,-2,1,-8}; | |
arrageNumber1(array); | |
arrageNumber(array); | |
} | |
// First way, Space complexity reduce. | |
private static void arrageNumber(int array[]){ | |
int value=0, a = 0; | |
for(int i =0;i<array.length;i++){ | |
value = array[i]; | |
if(value > 0) continue; | |
a = i-1 ; | |
while(a >=0 && array[a] >=0) | |
{ | |
array[a+1] = array[a]; | |
a = a -1; | |
} | |
array[a+1] = value; | |
} | |
System.out.print("call arrageNumber method"); | |
for(int i=0;i<array.length;i++){ | |
System.out.print(" "+array[i]); | |
} | |
} | |
//Second way, Time complexity reduce. | |
private static void arrageNumber1(int array[]){ | |
int index =0; | |
int [] newarray = new int[array.length]; | |
for(int i =0;i<array.length;i++){ | |
if(array[i] < 0){ | |
newarray[index++] = array[i]; | |
} | |
} | |
for(int i =0;i<array.length;i++){ | |
if(array[i] >= 0){ | |
newarray[index++] = array[i]; | |
} | |
} | |
System.out.print("call arrageNumber1 method"); | |
System.out.println(Arrays.toString(newarray)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This program asked in infostrech IT company for 2+ year experience