saha
BAN USERThe below solution is O(n) and I used Perl.
use strict;
use Data::Dumper;
my (@arr, @positives, @negatives, $no, $temp, $flag, $limit);
@arr = (1,-5,2,-4,6,-19,89);
foreach $no(@arr){
if($no > 0){
push(@positives, $no);
}else{
push(@negatives,$no);
}
}
@arr = ();
# Print the positives
# print Dumper @positives;
# Print the negatives
# print Dumper @negatives;
# Find the length of positives
my $len_positive = scalar @positives;
# Find the length of negatives
my $len_negative = scalar @negatives;
# Find the smallest array
if($len_positive < $len_negative){
$limit = $len_positive;
$flag = 1;
}else{
$limit = $len_negative;
$flag = 2;
}
foreach(my $i=0; $i< $limit; $i++){
push(@arr, $positives[$i]);
push(@arr, $negatives[$i]);
}
if($len_positive != $len_negative){
if($flag == 1) {
push(@arr,@negatives[$limit..$len_negative-1]);
}else{
push(@arr,@positives[$limit..$len_positive-1]);
}
}
print Dumper @arr;
I have solved the code using Perl.
- saha January 15, 2014