Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: How do i sort an numeric array without using sort function. Is ther any way to sort it just with loop in perl??

by choroba (Archbishop)
on Nov 02, 2017 at 09:34 UTC ( #1202586=note: print w/replies, xml ) Need Help??


in reply to How do i sort an numeric array without using sort function. Is ther any way to sort it just with loop in perl??

One of the simplest algorithms is the Gnome sort:
#!/usr/bin/perl use warnings; use strict; use feature qw{ say }; my @arr = (5, 3, 2, 1, 4); my $i = 0; while ($i < $#arr) { # Uncomment the following line to see the progress: # say STDERR "# @arr[ 0 .. $i ] * @arr[ $i + 1 .. $#arr ]"; if ($arr[$i] > $arr[$i+1]) { @arr[$i, $i+1] = @arr[$i+1, $i]; --$i if $i; } else { ++$i; } } say "@arr";

($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
  • Comment on Re: How do i sort an numeric array without using sort function. Is ther any way to sort it just with loop in perl??
  • Select or Download Code

Replies are listed 'Best First'.
Re^2: How do i sort an numeric array without using sort function. Is ther any way to sort it just with loop in perl??
by Tabish (Acolyte) on Nov 02, 2017 at 10:00 UTC

    If i do any mistake its bcs im new in perl

    I didnt get any output

    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @unsorted = map {int (1000 * rand ())} (1..100); my @sorted = sort_try (@unsorted); print Dumper \ @sorted; sub sort_try { my $i = 0; while ($i < $#unsorted) { if ($unsorted[$i] > $unsorted[$i+1]) { @unsorted[$i, $i+1] = @unsorted[$i+1, $i]; --$i if $i; } else { ++$i; } } return @unsorted; }

      You have written my @sorted = sort_try (@unsorted); but your sort_try sub doesn't return anything (and it also ignores its arguments but that's a different matter). Try reading perlsub for the basics.

        thank you very much that was really nice from you i got my answer :)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1202586]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (7)
As of 2021-06-21 16:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)












    Results (99 votes). Check out past polls.

    Notices?