Linear Search

 /// By using Array

#include <iostream>

using namespace std;


// Function to perform linear search on an array

int linearSearch(int arr[], int size, int key) 

{

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

        if (arr[i] == key) 

        {

            return i; // Return the index if key is found

        }

    }

    return -1; // Return -1 if key is not found

}


int main() {

    int arr[] = {10, 20, 30, 40, 50};

    int size = sizeof(arr) / sizeof(arr[0]);


    // Display the array

    cout << "Array: ";

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

        cout << arr[i] << " ";

    }

    cout << endl;


    // Perform linear search

    int key = 300;

    int index = linearSearch(arr, size, key);


    // Check if the element was found or not

    if (index != -1) {

        cout << "Element " << key << " found at index " << index << "." << endl;

    } else {

        cout << "Element " << key << " not found in the array." << endl;

    }


    return 0;

}


// By Using Linked List


#include <iostream>

using namespace std;


// Node structure for the linked list

struct Node {

    int data;

    Node* next;

};


// Function to perform linear search on linked list

Node* linearSearch(Node* head, int key) {


    Node* current = head;

    while (current != nullptr) {

        if (current->data == key) {

            return current; // Return the node if key is found

        }

        current = current->next;

    }

    return nullptr; // Return nullptr if key is not found

}


// Function to insert a node at the beginning of the linked list

Node* insert(Node* head, int data) {

    Node* newNode = new Node;

    newNode->data = data;

    newNode->next = head;

    return newNode;

}


// Function to display the linked list

void display(Node* head) {

    Node* temp = head;

    while (temp != nullptr) {

        cout << temp->data << " ";

        temp = temp->next;

    }

    cout << endl;

}


int main() {

    Node* head = nullptr;


    // Insert some elements into the linked list

    head = insert(head, 10);

    head = insert(head, 20);

    head = insert(head, 30);

    head = insert(head, 40);

    head = insert(head, 50);


    // Display the linked list

    cout << "Linked list: ";

    display(head);


    // Perform linear search

    int key = 300;

    Node* result = linearSearch(head, key);


    // Check if the element was found or not

    if (result != nullptr) {

        cout << "Element " << key << " found in the linked list." << endl;

    } else {

        cout << "Element " << key << " not found in the linked list." << endl;

    }


    return 0;

}


No comments:

Post a Comment

Fell free to write your query in comment. Your Comments will be fully encouraged.