dubbeat
dubbeat

Reputation: 7857

How to use Custom ordering on NSArray

How can I perfrom a custom sorting operation on an NSArray. I have one array of strings which is my ordering that I want.

NSArray A = {cat, dog, mouse, pig, donkey}

And I have one array of strings which is not ordered the way I want.

NSArray B = {dog,cat,mouse,donkey,pig}

Whats the best way to put array B in the same order as array A without having to use keys?

Upvotes: 1

Views: 820

Answers (4)

JeremyP
JeremyP

Reputation: 86671

Here's a way

NSArray *sortedArray = [B sortedArrayUsingComparator: ^(id obj1, id obj2){
    NSUInteger index1 = [A indexOfObject: obj1];
    NSUInteger index2 = [A indexOfObject: obj2];
    NSComparisonResult ret = NSOrderedSame;
    if (index1 < index2)
    {
        ret = NSOrderedAscending;
    }
    else if (index1 > index2)
    {
        ret = NSOrderedDescending;
    }
    return ret;
}];

The above will sort the elements of B into the same order as A with elements that are in B but not in A appearing at the end (since NSNotFound is a very big number). The only problem with the algorithm is that it multiplies the algorithmic complexity of the sort by O(n) where n is the number of objects in A. So for large A it will be pretty slow.

Upvotes: 7

Yogesh Maheshwari
Yogesh Maheshwari

Reputation: 1323

If you have:-

NSArray A = {cat, dog, mouse, pig, donkey}

and

NSMutableArray B = {dog,cat,mouse,donkey,pig}

you can use:-

[B sortArrayUsingComparator:^NSComparisonResult(NSString *obj1,   NSString *obj2) {
    NSUInteger indexOfObj1 = [A indexOfObject: obj1];
    NSUInteger indexOfObj2 = [A indexOfObject: obj2];
    if(indexOfObj1 == NSNotFound || indexOfObj2 == NSNotFound){
        return NSOrderedSame;
    }
    else if(indexOfObj1 > indexOfObj2){
        return NSOrderedDescending;
    }

    return NSOrderedAscending;
}];

Upvotes: 3

JDx
JDx

Reputation: 2655

Check out sortedArrayUsingComparator, always works for me!

Example:

NSArray *sortedArray = [B sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1,   NSString *obj2) {
    //Insert custom ordering code here, this will just sort alphabetically.
    return [obj1 compare:obj2];
}];

Upvotes: 0

touti
touti

Reputation: 1164

to add custom sorting the best way is to use sotring with function

NSArray *B=[A sortedArrayUsingFunction:sortingFunction context:nil];
//  sortingFunction

NSInteger sortingFunction( id obj1, id obj2, void *context){ if ( //your condition ){ return NSOrderedDescending; } if ( //your condition){ return NSOrderedAscending; } return NSOrderedSame; }

Upvotes: 0

Related Questions