Thread: sort arrays
View Single Post
Old 04-03-2003, 06:56 AM   #3 (permalink)
sno2dude
Registered User
 
sno2dude's Avatar
 
Join Date: Apr 2003
Location: Michigan Tech
Posts: 38
sno2dude is on a distinguished road
Send a message via AIM to sno2dude Send a message via Yahoo to sno2dude
Cool

or, if you dont wanna deal with the pain in the ass vector class. You can compare strings because they are comparable objects. i just had to do this for a project and it works quite well.

what you do is something like this where T is an array of srtings

for(int i=0; 1<T.length;i+=1){

index = i;
start = index + 1;
while(start<T.length){
int w = T[index].compareTo(T[start]);

if(w>0){
String temp=T[index];
T[index]=T[start];
T[start]=temp;
}
start += 1;
}
}


this will return T sorted by alphabetical order decending. Im pretty sure, i dont have my code here but that is what it is off the top of my head. the compareTo method returns 0 if two Strings are equal, a negative number if the first string precedes the second string alphabetically and a positive number if the second string precedes the first string alphabetically. It does this by comparing the ASCII values of the letters at each position til it (a) runs out of letters in one or both strings or (b) finds a point where they are different. If you want to sort it decending, then you just have to change w>0 to w<0.
sno2dude is offline   Reply With Quote