Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Working with arrays--Searching and Sorting Algorithms Task 1: Searching an Array

ID: 3745169 • Letter: W

Question


 Working with arrays--Searching and Sorting Algorithms

Task 1: Searching an Array Based List--Linear Search

Write a function that searches if a specific value exists in an array.  If the value is found, the function returns its index.  If the value is not in the array, it returns -1. Assume that the data in the array is not sorted.

Note: Swift has a build-in function called index(of:) that does the same thing.  However, our objective here is to study search algorithms.  So we're going to ignore it and write our own function.



Write an algorithm and verify it with an example


Implement it in Swift and test it.


Be ready to demo



Task 2: A More Efficient Search for Sorted Lists

Assume the list stored in the array is sorted in ascending order. How would you change your search algorithm to make more efficient?



Write an algorithm and verify it with an example


Implement it in Swift and test it


pls I need solutions. thanks


Explanation / Answer

//linear search

//BInary search

var lower = 0
var upper = a.count
while lower < upper {
let mid= lower + (upper - lower) / 2
if a[mid] == key {
return mid
} else if a[mid] < key {
lower = mid + 1
} else {
upper = mid
}
}
return -1
}

//any query, post in the comment section.

func BS<T: Comparable>(_ a: [T], key: T) -> Int? {
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote