Objective C: Sort Two Dimensional Array

*爱你&永不变心* 提交于 2019-12-01 01:27:22
Lily Ballard

This results in an infinite loop because, in every step, you're inserting two more values into the array. Thus your array is growing faster than you are traversing it. I'm assuming you meant to swap the values.

In any case, a much simpler and more efficient sort is to use the built-in sorting capabilities:

// NSArray *sortedArray, with the unsorted 'array' pulled from some other instance
sortedArray = [array sortedArrayUsingComparator:^(id a, id b) {
    return [[b objectAtIndex:0] compare:[a objectAtIndex:0]];
}];

If array is mutable and you want to sort it in place:

[array sortUsingComparator:^(id a, id b) {
    return [b[0] compare:a[0]];
}];

If array is immutable or you want to leave it alone and make a sorted copy:

NSArray *sortedArray = [array sortedArrayUsingComparator:^(id a, id b) {
    return [b[0] compare:a[0]];
}];
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!