Link to home
Start Free TrialLog in
Avatar of sanjangeorge
sanjangeorge

asked on

Sortting an array

I have a list of names like this.

[0]Bob
[1]Joe
[2]Bob
[3]Bob
[4]Bob
[5]Joe
[6]Phil
[7]Phil

I want to sort my array without changing it so that its like this (so basically give an alternative index of elements so its like this):

[0]Bob
[2]Bob
[3]Bob
[4]Bob
[1]Joe
[5]Joe
[6]Phil
[7]Phil

#Class contains the name information.
 
$m=0;
$no=0;
$kl =0;
@keep=();
 
foreach (@Class){
	$test = $no;
		foreach $u (0..$#keep){
			if ($_=~m/$keep[$u]/){
				$no++;
			} elsif ($_ =~ m/^[ \t]*$/){
				$Class[$m]="CHECK MANUALLY";
			}
		}
		if ($no==$test){
		$keep[$kl] = $_;
		$kl++;
		}
	$m++;
}
 
@keep2=();
@index =();
$indcount=0;
foreach $hu (@keep){
 
	foreach $ij (0..$#Class){
		if ($Class[$ij] =~ m/$hu/){
			$index[$indcount]=$ij;
			$indcount++;
		}
	}
	
}

Open in new window

Avatar of kawas
kawas
Flag of United States of America image

To sort an array in ASCII (Alphabetical) order :
sort(@array);

Example of storing a sort result back into the same array :
@array = sort (@array);

To sort an array in reverse ASCII (Alphabetical) order :
sort {$b cmp $a} (@array);

To sort an array in numeric ascending order :
sort {$a <=> $b} (@array);

To sort an array in numeric decending order :
sort {$b <=> $a} (@array);

To print a sorted array but not alter the original :
print sort(@array);

To reverse the value elements in an array :
reverse (@array);


from http://www.htmlite.com/perl016.php
Avatar of sanjangeorge
sanjangeorge

ASKER

Yeah i've seen things like this not quite what im looking for
if you are trying to sort the arrays and keep indices (old and new) maybe the data structure you are using isnt correct for you.

#!/usr/bin/perl -w
use strict;
 
my @unsorted = (
             "[0]Bob",
             "[1]Joe",
             "[2]Bob",
             "[3]Bob",
             "[4]Bob",
             "[5]Joe",
             "[6]Phil",
             "[7]Phil"
             );
 
my @sorted = sort {
   $a =~ /^\[(\d+)\](.*)$/ or die "input $a not in expected form\n";
   my ($a1, $a2) = ($1, $2);
   $b =~ /^\[(\d+)\](.*)$/ or die "input $b not in expected form\n";
   my ($b1, $b2) = ($1, $2);
   $a2 eq $b2 ? $a1 <=> $b1 : $a2 cmp $b2;
} @unsorted;
 
print join("\n", @sorted)."\n";

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Adam314
Adam314

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ozo
my @unsorted = (
             "[0]Bob",
             "[1]Joe",
             "[2]Bob",
             "[3]Bob",
             "[4]Bob",
             "[5]Joe",
             "[6]Phil",
             "[7]Phil"
             );
$\=$/;
print for @sorted = map{/\0(.*)/}sort map{join"\0",(/([][\d]*(.*))/)[1,0]} @unsorted ;