Keep in mind that bubble sort is one of the worst known sorting approaches. But given that, here's your sort (I gotta stop answering homework questions...)

This isn't even an EFFICIENT bubble sort (hehe), since "isSorted" could be done as part of the bubbling loop, by bubbling until no swaps occur. But this version is probably easier to read.

sub bubble { my $arrRef=shift; foreach my $i(1..@$arrRef-1) { @$arrRef[$i,$i-1]=@$arrRef[$i-1,$i] unless $arrRef->[$i-1]<=$arrRef->[$i]; } } sub isSorted { my $arrRef=shift; my $isSorted=0; foreach my $i(1..@$arrRef-1) { return 0 unless $arrRef->[$i-1]<=$arrRef->[$i]; } return 1; } open(IN,"<raw_data") or die "Can't open raw_data, error $!"; my @raw_data=map {chomp;$_} <IN>; print "Before sort: ",(join ",",@raw_data), "\n"; bubble(\@raw_data) while !isSorted(\@raw_data); print "After sort: ",(join ",",@raw_data), "\n";

If this IS for homework, try to understand it before handing it in, k? Otherwise, your teacher's gonna ask you some tough questions, and you're going to be in deep trouble...

Besides, if your teacher likes perl enough to teach it, he probably hangs out here with us anyhow :)
--
Mike


In reply to Re: bubble sort in perl by RMGir
in thread bubble sort in perl by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.