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