Skip to content

Instantly share code, notes, and snippets.

@pradeeprajkumar
Last active May 12, 2018 20:57
Show Gist options
  • Select an option

  • Save pradeeprajkumar/b16f840b8818cd122eedf162aa97fb22 to your computer and use it in GitHub Desktop.

Select an option

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.
func linearSearch<T: Equatable>(array: [T], object: T) -> [Int] {
let resultArray = array.indices.filter { (index) -> Bool in
array[index] == object
}
return resultArray
}
@pradeeprajkumar
Copy link
Author

pradeeprajkumar commented Sep 6, 2016

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:

let array = [5, 2, 4, 7]
array.contains(4)

The above code returns true.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment