Pages

Saturday, August 28, 2010

Linear Searching

Linear Searching 
The following C++ code will explains the implementation of Linear Searching and sort the user input numbers in descending order.
The following implementation is in object oriented using the LinearSearching class and ls object. Actual logic of Linear Searching is in the function of LSearching().
Remember in Linear Searching, bubble sort is used to sort the data and to search in the sorted data Linear Searching is used.


In LinearSearching.h

#include <iostream>
using namespace std;

class LinearSearching
{
public:
    static const int N = 11;
    int arr[N];

public:
    void BSort(int *arr)
    {
        for (int i = 0; i <= N-1; ++i)
        {
            for (int j = i+1; j <= N-1; ++j)
            {
                if (arr[i] > arr[j])        //Descending (small to big)
                {
                    int temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
    }

    void LSearching(int *arr, int target)
    {
        int flag = 0;
        for (int k = 0; k <= N - 1; ++k)
        {
            if (arr[k] == target)
            {
                cout << "\nValue " << target << " found at index (from 1 to 11) : " << k + 1;
                flag = 1;
            }
        }
        if (flag == 0)
            cout << "\nValue you want to search is not exist in your input numbers.";
    }
};



In main.cpp
 
#include "LinearSearching.h"
int main()
{
    LinearSearching ls;

    for (int i = 0; i <= 10; ++i)
    {
        cout << "Enter values in array : " << i+1 << " of 11: ";
        cin >> ls.arr[i];
    }
    ls.BSort(ls.arr);
    cout << "\n\nAfter Bubble Sort input numbers are\n";
    for (int i = 0; i <= 10; ++i)
    {
        cout << ls.arr[i] << "\t";
    }
    char ch = 'y';
    while ((ch == 'y') || (ch == 'Y'))
    {
        int n;
        cout << "\n\nEnter a number to search in sorted array: ";
        cin >> n;
        ls.LSearching(ls.arr, n);

        cout << "\nDo you want to search again : (y/n) : ";
        cin >> ch;
    }
    return 0;
}





Feel free to comment with your questions and suggestions regarding the post content...!

No comments:

Post a Comment

Your valuable comments are appreciated...!