Jump to content

Quick sort help in perl

- - - - -

  • Please log in to reply
2 replies to this topic

#1
hsincredible

hsincredible

    Newbie

  • Members
  • Pip
  • 1 posts
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";

}


#2
ReignInChaos

ReignInChaos

    Learning Programmer

  • Members
  • PipPipPip
  • 46 posts
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.

#3
debtboy

debtboy

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 916 posts
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";
}





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users