Perl Programming – Bubble Sort a String

After getting familiar with the syntax of a language, performing little challenges - such as sorting a list of items - is often the next thing one might try. So, although I'd previously lots of Perl experience, having focused on other things for a while I was decidedly rusty, and decided to reactivate my Perl braincells, and write a little program to bubble sort a string in Perl.

So, there are no doubt many ways to do something like this and, in Perl especially, there are many ways to write super-succinct code. With that in mind, this code is definitely not the shortest or most efficient (and bubble-sorts are rather inefficient to begin with!), but hopefully it is quite readable and easy to follow. A project for yourself would be to see how you can improve it.

#!/usr/bin/perl

# Bubble-sort a string in Perl

use strict;
use warnings;

my $string = "zjeifopwdjqeqw";
print "$string\n";

for (my $z=0; $z<length($string); $z++)
{
  my $temp1=''; my $temp2='';

  for (my $i=0; $i<length($string); $i++)
  {
    if ( ord(substr($string,$i+1)) >= ord(substr($string,$i,1)) )
    {
    next;
    }
    else
    {
    $temp1=substr($string,$i,1);
    $temp2=substr($string,$i+1,1);
    substr($string,$i+1,1)=$temp1;
    substr($string,$i,1) = $temp2;
    }
  }
}

print "$string\n";

exit;

Which, with the string provided, will print this:

$ perl bubble.pl
zjeifopwdjqeqw
deefijjopqqwwz

I hope you'll have fun playing around with the code, and making even better versions. Bubble-sorting can be useful on occasion, although in this case it was just a little program to shake some dust off the braincells.

If you really wanted to just reverse a string in Perl, then you could simply use the reverse keyword, per the example below, but - of course - that's not the same as sorting a string.

#!/usr/bin/perl

use strict;
use warnings;

my $string = "ABCDEFG";

print "$string\n";
my $reversed = reverse $string;
print "$reversed\n";

exit;

... which will print this:

$ perl reverse.pl
ABCDEFG
GFEDCBA