Computer Science Module 1 Question 2(Searching)

Zachary Kublalsingh

Unit2

Jul 13, 2024

Estimated reading time:


Contains all relevant information regarding searching of lists, linear and binary.




Linear Search

Traverses a list entirely, comparing the search value to each element in the list until either the search value is found, returning its index or it traverses the entire list, displaying that the element was not found.

Code


int linear_search(int arr\[], int n, int x) 

{

    for (int i = 0; i < n; i++) {

        if (arr\[i] == x) {

            return i; // Element found, return its index

        }

    }

    return -1; // Element not found

}

Binary Search

Code


int binary_search(int arr\[], int n, int x) {

    for (int i = 0; i < n; i++) {

        if (arr\[i] == x) {

            return i; // Element found, return its index

        }

    }

    return -1; // Element not found

}

⚠️ Did you spot an error? Contact Us!
Please include the title of the note, the respective Notebook and the error to speed up the process.

Read Next

Dont't forget to check out our Instagram Page!
edukatte_tt