0% found this document useful (0 votes)
16 views1 page

DSA Part 04

The document describes two searching algorithms: Linear Search and Binary Search. Linear Search has a time complexity of O(n) and space complexity of O(1), while Binary Search is more efficient with a time complexity of O(log n) and the same space complexity of O(1). Both algorithms return the index of the target element if found, or nil if not found.

Uploaded by

adsurerahul96
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views1 page

DSA Part 04

The document describes two searching algorithms: Linear Search and Binary Search. Linear Search has a time complexity of O(n) and space complexity of O(1), while Binary Search is more efficient with a time complexity of O(log n) and the same space complexity of O(1). Both algorithms return the index of the target element if found, or nil if not found.

Uploaded by

adsurerahul96
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Searching Algorithms

Linear Search
func linearSearch(_ array: [Int], _ target: Int) -> Int? {​
for (i, val) in array.enumerated() {​
if val == target {​
return i​
}​
}​
return nil​
}​
// Time: O(n), Space: O(1)

Binary Search
func binarySearch(_ array: [Int], _ target: Int) -> Int? {​
var low = 0, high = array.count - 1​
while low <= high {​
let mid = (low + high) / 2​
if array[mid] == target { return mid }​
else if array[mid] < target { low = mid + 1 }​
else { high = mid - 1 }​
}​
return nil​
}​
// Time: O(log n), Space: O(1)

You might also like