Last active
May 12, 2018 20:57
-
-
Save pradeeprajkumar/b16f840b8818cd122eedf162aa97fb22 to your computer and use it in GitHub Desktop.
This method does a Linear search in an array and returns the index of the object in the array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| func linearSearch<T: Equatable>(array: [T], object: T) -> [Int] { | |
| let resultArray = array.indices.filter { (index) -> Bool in | |
| array[index] == object | |
| } | |
| return resultArray | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Linear search:
Usage: print(linearSearch(array: [1.0,2.0,3.0,4,5,3,4], object: 2.0))Function returns the indices that contains the search value.
If we just want to know whether the object is present in the array or not, then we can use the "contains" method.
Example:
The above code returns true.