Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

DS LAB WORKSHEET

Experiment-1.2

Student Name: Navya Jain Date: 26-08-22


Group: 811-A Subject code : 21CSH-211
UID: 21BCS5701
Subject: Data Structures

Aim: WRITE A PROGRAM TO DEMONSTRATE THE USE OF LINEAR AND BINARY


SEARCH TO FIND A GIVEN ELEMENT IN AN ARRAY.

Algorithm : Algorithm of Question 1 :

1. Start

2. Write the elements of array

3. Write number to search

4. If arr[i]==num

5. Return the number and store it in variable called index

6. Print Index

7. Exit.

Algorithm of Question 2 :

1) Start

2) Write elements of array

3) Write number to be searched

4) First =0

5) Last=9

6) Do mid=(first+last)/2

7) If a[mid]==num

8) Print mid
DS LAB WORKSHEET

9) Else if a[mid]<num

10) First =mid+1

11) Else last=mid-1

12) While (first<=last)

13) If (first>last)

14) Print

15) Exit

Program Code:

1) Linear Search Program:

2) #include <iostream>
3) using namespace std;
4) int main()
5) {
6)     int arr[5], num, index;
7)     cout << " Enter 5 elements :";
8)     for (int i = 0; i < 5; i++)
9)         cin >> arr[i];
10)     cout << " Enter number to search : ";
11)     cin >> num;
12)     for (int i = 0; i < 5; i++)
13)     {
14)         if (arr[i] == num)
15)         {
16)
17)             index = i; // returning the number what we have founded
18)             cout << " Found at index number " << index;
19)             break;
20)         }
21)     }
22)
23)     return 0;
24) }

Binary Search Program:

#include <iostream>
DS LAB WORKSHEET

using namespace std;


int main()
{
    int arr[5], mid, first, last, a;
    cout << " Enter elements of array :";
    for (int i = 0; i < 5; i++)
        cin >> arr[i];
    cout << " Enter element to be searched :";
    cin >> a;
    do
    {
        mid = (first + last) / 2;
        if (arr[mid] == a)
        {

            cout << " Element found at index " << mid;


            break;
        }

        else if (arr[mid] < a)


        {
            first = mid + 1;
        }
        else
            last = mid - 1;
    } while (first<=last);

    return 0;
}

Output :
DS LAB WORKSHEET

Time and Space complexity: Time complexity for linear search of array is order
of n i.e., O(n). Time-complexity for binary search of array is order of log n. i.e.,
O(log n).

You might also like