我有一个从通讯簿中检索到的联系人列表,该列表存储在MutableArray contactList中。每个联系人都是一个具有“ contactName,contactImage ....等”属性的对象。
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{
//getAllContacts is a method which returns a Mutable array of Objects
self.contactList = [NSMutableArray arrayWithArray:[instance getAllContacts]];
//groupLetterToLoad could be "DEF"
for(int j=0; j<self.groupLetterToLoad.length;j++) {
//1st iteration D, 2nd iteration E and 3rd iteration F
NSString *testChar = [NSString stringWithFormat:@"%c",[self.groupLetterToLoad characterAtIndex:j]];
//check D,E,F with contact name property's first letter of the contact list array
for(int i=0;i<self.contactList.count;i++) {
NSString *firstChar =[[[self.contactList objectAtIndex:i] contactName] substringToIndex:1];
if([testChar isEqualToString: firstChar]) {
pos=i; //retrieve the index of the matched position
break;
}
}
if(pos!=-1) break;
}
});
现在它有两个for循环(时间O(n ^ 2))。这里的缺点是,如果groupLetterToLoad为“ WXYZ”,则比较将从A的W到Z的W进行比较。如何优化它?
contactName
如果可以避免每次搜索都[instance getAllContacts]
进行排序(提示:保持排序),则对数组进行排序并执行半间隔搜索将大大降低您的复杂性。
http://rosettacode.org/wiki/Binary_search#Objective-C-这是一个起点。您可以用compare:
第一个字符比较替换。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句