Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Quick sort help in perl


  • Please log in to reply
2 replies to this topic

#1 hsincredible

hsincredible

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 31 May 2011 - 05:29 AM

can anyone please help... whats wrong with my algo here : its a perl program for quick-sort. O/P is wrong
sample i/p:
6
3
8
1
6
5
4
o/p:
1
1
4
4
4
4

#!/usr/bin/perl
my $t=<STDIN>;
int($t);
my @n;
while($t)
{
        push(@n,int(<STDIN>));
        $t--;
}
&quick(0,$#n);
sub quick
{
  if($_[0]<$_[1])
  {
        my $pivot = $n[$_[1]];
        my $from = $_[0];
        my $to = $_[1];
        my $i=$from-1;
        my $j=$from;
        my $temp;
        while($j<$to)
        {
                if($n[$j]<=$pivot)
                {
                        $i=$i+1;
                        $temp=$n[$i];
                        $n[$i]=$n[$j];
                        $n[$j]=$temp;
                }
                $j=$j+1;
        }
        $i=$i+1;
        $temp=$n[$i];
        $n[$i]=$pivot;
        $pivot=$n[$i];
        &quick($from,$i-1);
        &quick($i+1,$to);
  }
}
foreach(@n)
{
        print $_."\n";
}

  • 0

#2 ReignInChaos

ReignInChaos

    CC Regular

  • Just Joined
  • PipPipPip
  • 44 posts

Posted 08 July 2011 - 05:28 AM

I'd run this through the perl debugger or at least have a couple print statements to see whats going on. Perl can be very tricky with the scalar and array notation especially working with $_. But in my opinion run this though the perl debugger and you will probably see whats wrong.
  • 0

#3 debtboy

debtboy

    CC Devotee

  • Just Joined
  • PipPipPipPipPipPip
  • 499 posts

Posted 24 July 2011 - 06:11 AM

Hi hsincredible,
(I just saw this post)

I assume you have a reason for the way you collect data from STDIN...
number of inputs then inputs :confused:

Perl is an awesome language for extracting and manipulating data.
A sort function already exists and produces a sorted output.


#!/usr/bin/perl

my $t=<STDIN>;
int($t);
my @n;
my @n_sorted;
while($t)
{
        push(@n,int(<STDIN>));
        $t--;
}
@n_sorted = sort @n;
foreach(@n_sorted)
{
        print $_."\n";
}

  • 0