简体   繁体   中英

Sort NSArray for a specific order

I have an NSArray of custom objects. Each object contains one integer value for ex. 1,2,3,4

Now I want to sort Array like below

9 7 5 3 1 2 4 6 8

Could some one help me?

Here is your answer.

Hope your first array is in sorted order (ascending) if not then you need to sort it first.

NSMutableArray *myArray = [NSMutableArray array];

//Populate your array with custom objects. I had created my own which contain an integer type property.

[myArray addObject:[[myObject alloc] initWithId:11 objectName:@"K"]];
[myArray addObject:[[myObject alloc] initWithId:3 objectName:@"C"]];
[myArray addObject:[[myObject alloc] initWithId:4 objectName:@"D"]];
....
...
.... and so on

then sort it in Ascending order. You can do it Descending also but then you need to change the below logic little bit. I showing with Ascending order.

NSArray *tempArray = [myArray sortedArrayUsingComparator:^NSComparisonResult(myObject *obj1, myObject *obj2) {
        if([obj1 objectId] > [obj2 objectId]) return NSOrderedDescending;
        else if([obj1 objectId] < [obj2 objectId]) return NSOrderedAscending;
        else return NSOrderedSame;
}];

Now sort them as per your requirement

NSMutableArray *finalArray = [NSMutableArray arrayWithArray:tempArray];

NSInteger totalObjects = [tempArray count];
NSInteger centerObjectIndex = totalObjects>>1;
__block NSInteger rightPosition = centerObjectIndex + 1;
__block NSInteger leftPosition = centerObjectIndex - 1;
__block BOOL toggle = NO;



[tempArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    if(idx == 0) [finalArray replaceObjectAtIndex:centerObjectIndex withObject:obj];
    else
    {
        if(toggle)
        {
            if(leftPosition >= 0)
            {
                [finalArray replaceObjectAtIndex:leftPosition withObject:obj];
                leftPosition -= 1;
            }
        }
        else
        {
            if(rightPosition < totalObjects)
            {
                [finalArray replaceObjectAtIndex:rightPosition withObject:obj];
                rightPosition += 1;
            }
        }
        toggle = !toggle;
    }
}];

Here is the final step if your array contains an even numbers of objects

if(!(totalObjects % 2))
{
    [finalArray removeObjectAtIndex:0];
    [finalArray addObject:[tempArray objectAtIndex:totalObjects-1]];
}

Now you are at end. Your array named finalArray get sorted as per your requirement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM