Menu

Post image 1
Post image 2
1 / 2
0

O(log n) & O(n log n): Search and Sort Masters

DEV Community·Utku Catal·19 days ago
#ydafUBGT
Reading 0:00
15s threshold

Searching and sorting power modern applications. O(log n) and O(n log n) represent optimal efficiency for these tasks. Knowing them is the difference between a search that returns instantly and one that crawls. O(log n): Binary Search Halves the search space each step. Logarithmic growth. To find an element among 1 million sorted items, only ~20 comparisons. func binarySearch ( arr [] int , target int ) int { left , right := 0 , len ( arr ) - 1 for left <= right { // log n iterations mid := left + ( right - left ) / 2 if arr [ mid ] == target { return mid } if arr [ mid ] < target { left = mid + 1 } else { right = mid - 1 } } return - 1 } Enter fullscreen mode Exit fullscreen mode The trick: with each iteration, half of the remaining candidates are eliminated. Requires a sorted input. O(n log n): Merge Sort Divide-and-conquer: splits array, sorts halves, merges. Industry standard for general-purpose sorting.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More