Data Structures - 9

AIM: Write C Program to implement searching algorithms for the following:


1. SequentialSearch( )

 

#include<stdio.h>

#include<conio.h>

#define SIZE 5

 

int seq_search(int ele[], int item)

{

    int i = -1;

    int j = 0;

 

    for (j = 0; j < SIZE; j++) {

        if (ele[j] == item) {

            i = j;

            break;

        }

    }

    return i;

}

 

int main()

{

    int ele[SIZE];

    int i = 0;

    int item;

    int pos;

    printf("\n------ Enter Values ------ \n\n");

 

    for (i = 0; i < SIZE; i++) {

        printf("Enter element [%d]: ", i + 1);

        scanf("%d", &ele[i]);

    }

 

    printf("\n\nEnter the element to be searched  : ");

    scanf("%d", &item);

 

    pos = seq_search(ele, item);

 

    if (i >= 0) {

        printf("\nSearch is Successful\n", i + 1);

    }

    else {

        printf("\nSearch is UnSuccessful\n");

    }

    return 0;

}




 

 


 2. BinarySearch( )

 

#include<stdio.h>

#include<conio.h>

 

int main()

{

    int i, arr[5], search, first, last, middle;

    printf("Enter the elements : \n");

    printf("(The sequence should be in ascending order) \n\n");

    for(i=0; i<5; i++)

        scanf("%d", &arr[i]);

    printf("\nEnter element to be search: ");

    scanf("%d", &search);

    first = 0;

    last = 4;

    middle = (first+last)/2;

    while(first <= last)

    {

        if(arr[middle]<search)

            first = middle+1;

        else if(arr[middle]==search)

        {

            printf("\nSearch is Successful\n", search, middle+1);

            break;

        }

        else

            last = middle-1;

        middle = (first+last)/2;

    }

 

    if(first>last)

        printf("\nSearch is UnSuccessful\n", search);

    return 0;

}




Comments

Popular posts from this blog

Computer Architecture and Organization - 4

Design and Analysis of Algorithms - 2

Design and Analysis of Algorithms - 6

Design and Analysis of Algorithms - 1

Artificial Intelligence - 7