Swift Program to Implement Linear Search

Swift Program to Implement Linear Search

Linear Search is one of the simplest and most straightforward search algorithms. It works by checking each element of a list one by one until the desired value is found or the list ends. Even though it is not the most efficient search method for large datasets, its simplicity makes it a perfect starting point for beginners learning how search algorithms work. Linear Search can be applied to arrays, lists, or any collection that can be accessed sequentially.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Linear Search is widely used in situations where data is unsorted or when the dataset is small. Its main advantage is that it does not require the elements to be in any particular order. Understanding Linear Search also helps beginners grasp the basic principles of algorithmic thinking, including iteration, condition checking, and returning results efficiently.

Program 1: Linear Search Using a For Loop

This program demonstrates the classic approach to Linear Search using a simple for loop. It searches for an integer in an array and returns its position.

import Foundation

func linearSearch(array: [Int], target: Int) -> Int? {

    for (index, value) in array.enumerated() {

        if value == target {
            return index
        }

    }

    return nil

}

let numbers = [10, 23, 45, 70, 11, 15]

if let index = linearSearch(array: numbers, target: 70) {
    print("Found 70 at index:", index)
} else {
    print("70 not found")
}

This method loops through each element and checks if it matches the target. Beginners can see how iteration and conditionals work together to search efficiently through small datasets.

Program 2: Linear Search Using While Loop

In this version, Linear Search is implemented using a while loop. It demonstrates another way to iterate through an array.

import Foundation

func linearSearchWhile(array: [Int], target: Int) -> Int? {

    var index = 0

    while index < array.count {

        if array[index] == target {
            return index
        }

        index += 1

    }

    return nil

}

let numbers2 = [5, 12, 9, 21, 33]

if let index = linearSearchWhile(array: numbers2, target: 21) {
    print("Found 21 at index:", index)
} else {
    print("21 not found")
}

Using a while loop helps beginners understand how a search can progress with manual control over the loop index, which is useful when more complex conditions or modifications are required during iteration.

Program 3: Recursive Linear Search

This program shows how Linear Search can be implemented recursively. Recursion breaks the problem into smaller subproblems until the target is found.

import Foundation

func recursiveLinearSearch(array: [Int], target: Int, index: Int = 0) -> Int? {

    if index >= array.count {
        return nil
    }

    if array[index] == target {
        return index
    }

    return recursiveLinearSearch(array: array, target: target, index: index + 1)

}

let numbers3 = [3, 6, 9, 12, 15]

if let index = recursiveLinearSearch(array: numbers3, target: 12) {
    print("Found 12 at index:", index)
} else {
    print("12 not found")
}

Recursion helps beginners understand breaking a task into smaller, repeatable actions. Although it uses more memory than loops, recursive Linear Search is elegant and readable for small datasets.

Program 4: Linear Search for Strings

Linear Search is not limited to numbers. This example searches for a string in an array of names.

import Foundation

func linearSearchStrings(array: [String], target: String) -> Int? {

    for (index, value) in array.enumerated() {

        if value == target {
            return index
        }

    }

    return nil

}

let names = ["Alice", "Bob", "Charlie", "Diana"]

if let index = linearSearchStrings(array: names, target: "Charlie") {
    print("Found Charlie at index:", index)
} else {
    print("Charlie not found")
}

Beginners can see that the same Linear Search logic applies to any comparable data type, whether numbers, strings, or other objects, making it a versatile algorithm.

Program 5: Linear Search in Tuples Using a Key

Here, Linear Search is applied to tuples, allowing search based on a specific attribute, such as a score or age.

import Foundation

func linearSearchTuples(array: [(String, Int)], target: Int) -> Int? {

    for (index, tuple) in array.enumerated() {

        if tuple.1 == target {
            return index
        }

    }

    return nil

}

let students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]

if let index = linearSearchTuples(array: students, target: 92) {
    print("Found student with score 92 at index:", index)
} else {
    print("Score 92 not found")
}

By using a key within tuples, beginners learn how Linear Search can adapt to more complex data structures while still keeping the algorithm simple and clear.

Frequently Asked Questions (FAQ)

This section clears common doubts and provides quick answers.

Q1: When should I use Linear Search?
Linear Search is best for small or unsorted datasets. It’s simple and easy to implement.

Q2: Is Linear Search efficient for large datasets?
Linear Search has O(n) complexity, so it becomes inefficient as datasets grow. For large data, consider Binary Search or hash-based searching.

Q3: Can Linear Search be used with strings?
Yes, Linear Search works with strings, tuples, or any comparable type.

Q4: Is Linear Search stable?
Yes, Linear Search preserves the order of elements if duplicates exist.

Q5: Can Linear Search be recursive?
Yes, as shown in Program 3, recursion is an alternative to loops, though it may use more memory.

Conclusion

Linear Search is a simple and beginner-friendly algorithm that introduces the basics of searching in a dataset. By using loops, recursion, and working with different types of data, beginners can quickly understand how searching works. It is versatile, easy to implement, and a perfect starting point before exploring more advanced search algorithms. Practicing Linear Search helps strengthen programming fundamentals and builds confidence to tackle larger, more complex problems.

Scroll to Top