Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Simple bubble sort

by clintp (Curate)
on Sep 20, 2001 at 05:45 UTC ( [id://113512]=note: print w/replies, xml ) Need Help??


in reply to Simple bubble sort

I'll let the others lecture you about bubble sorts. Lemme take this opportunity to show you something cool in Perl. See this code of yours:
my $temp = @$array[$index + 1]; @$array[$index + 1] = @$array[$index]; @$array[$index] = $temp;
Things that follow the form:
t=a; a=b; b=t;
Can be reduced in Perl to:
(a,b)=(b,a);
So shorten that block of code to:
($array->[$i+1],$array->[$i])= ($array->[$i],$array->[$i+1]);

Replies are listed 'Best First'.
Re: Re: Simple bubble sort
by blakem (Monsignor) on Sep 20, 2001 at 09:22 UTC
    Since we can assign into an array slice, it can be shortened down to something like:
    @$array[$i,$i+1] = @$array[$i+1,$i];
    See it in action below....
    #!/usr/bin/perl -wT use strict; my $arrayref = ['A','B','C','D']; print "Before: ", join(' ',@$arrayref), "\n"; @$arrayref[1,2] = @$arrayref[2,1]; # assign into an array slic +e print "After : ", join(' ',@$arrayref), "\n"; =output Before: A B C D After : A C B D

    -Blake

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://113512]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2024-04-24 13:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found