Do you really need to sort to verify this? Consider the algorithm.
create 2 counter arrays, ac and bc, both of size 128
initialize them with 0
for each char c in string a make ac [c] ++
for each char c in string b make bc [c] ++
if all 128 counters in ac and bc are same, then they r permutation of one another
It may even work faster than sorting.
EDIT: This is a possible implementation. Since I did not compile the code, there may be small errors.
- (BOOL) isPermutation: (NSString *) string1 ofString: (NSString *) string2 {
if ([string1 length]! = [string2 length]) {
return FALSE;
}
NSInteger counter1 [128];
NSInteger counter2 [128];
NSInteger i;
NSInteger len = [string1 length];
for (i = 0; i <128; i ++) {
counter1 [i] = counter2 [i] = 0;
}
for (i = 0; i <len; i ++) {
unichar ch1 = [string1 characterAtIndex: i];
unichar ch2 = [string2 characterAtIndex: i];
counter1 [ch1] ++;
counter2 [ch2] ++;
}
for (i = 0; i <128; i ++) {
if (counter1 [i]! = counter2 [i]) {
return FALSE;
}
}
return TRUE;
}
source share