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
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.