How is what you want to do different than a Bubble Sort where you stop on the first swap? A bubble sort moves the highest element up by one position for each pass (here a digit). What do you want to happen if the highest number is already first in the order?
Update:
Probably a better way to get the index of max value...But is this what you want?
Code should run fairly quickly albeit a bit wordy for Perl.
#!/usr/bin/perl
use strict;
use warnings;
my @array = split '', "117";
print @array, "\n";
print @array,"\n" while rot_max_left(\@array);
@array = split '', "1234";
print "\n",@array,"\n";
print @array,"\n" while rot_max_left(\@array);
sub rot_max_left
{
my $array_ref = shift;
my $maxi=0;
return 0 unless ($maxi = get_index_of_max($array_ref));
($array_ref->[$maxi-1],$array_ref->[$maxi]) = ($array_ref->[$maxi]
+,$array_ref->[$maxi-1]);
return $maxi;
}
sub get_index_of_max
{
my $array_ref = shift;
my $maxi = 0;
foreach (my $i=1;$i<@$array_ref;$i++)
{
$maxi = $i if ($array_ref->[$i] > $array_ref->[$maxi])
}
return $maxi;
}
__END__
117
171
711
1234
1243
1423
4123
|