我有NSArray
个自定义对象。
每个对象包含一个整数值。 1,2,3,4
现在我想按下面的方式对数组进行排序
9 7 5 3 1 2 4 6 8
有人可以帮助我吗?
答案 0 :(得分:0)
这是你的答案。
希望你的第一个数组按排序顺序(升序),否则你需要先排序。
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
然后按Ascending
顺序对其进行排序。你也可以Descending
,但是你需要改变下面的逻辑。我以Ascending
订单显示。
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;
}];
现在根据您的要求对它们进行排序
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;
}
}];
如果您的数组包含偶数个对象,那么这是最后一步
if(!(totalObjects % 2))
{
[finalArray removeObjectAtIndex:0];
[finalArray addObject:[tempArray objectAtIndex:totalObjects-1]];
}
现在你已经结束了。您的名为finalArray
的数组将根据您的要求进行排序。