2016-05-27 38 views
0

我有一个排序的字符串数组。在这个数组中有没有一种快速查找和元素的方法?在排序数组中快速找到元素

我想优化以下功能。这需要很长时间。传递的数组不长(只有约15-20元),但它被称为很多(约1000倍)。目前我只是做了.filter { }但我认为这可能是一个瓶颈,因为它经过了全阵列1000次而不是在找到第一个这样的日历时发生。

是否有被优化一个内置的搜索(即,使用非常小的阵列然后中型或较大的一种不同的方法)类似内置排序功能?

基本上,我在寻找对方的内置分页/排序功能。这样做会很有意义,因为您经常对数组进行排序,然后在其中查找特定的元素。

func startsWithACalendarName(text: String, calendars: [EKCalendar], stripKeywords: Bool = false) -> (newReminderText: String, foundCalendar: EKCalendar?) { 
    // make array of words from text 
    let words = text.characters.split{$0 == " "}.map(String.init) 
    // BOTTLENECK? Check if I have a calendar that is equal to first word of text 
    let found = calendars.filter { $0.title.lowercaseString == words.head?.lowercaseString } 
    return (stripKeywords ? (words.tail?.joinWithSeparator(" "))! : text, found.first) 
} 
+0

问题标题是如何与这个问题的身体吗? –

+0

对不起,更正了。 – Daniel

+1

如果已经排序,您可以使用二进制搜索。 –

回答

0

我认为你可以解决的,而不是“过滤器”这个使用“的indexOf”:

func startsWithACalendarName(text: String, calendars: [EKCalendar], stripKeywords: Bool = false) -> (newReminderText: String, foundCalendar: EKCalendar?) { 
    let words = text.characters.split{$0 == " "}.map(String.init) 
    var found: EKCalendar? 
    if let index = calendars.indexOf ({ $0.title.lowercaseString == words.head?.lowercaseString }) { 
     found = calendars[index] 
    } 
    return (stripKeywords ? (words.tail?.joinWithSeparator(" "))! : text, found) 
} 
+0

但是,这是否考虑到数组已经排序?因为搜索排序数组要比在非排序数组中搜索索引快得多。 – Daniel

+0

它应该比使用'filter'更好。在这一点上,我会做一个小测试来衡量两者的运行时间,看看它是否足够好。 – orxelm