Pages

Saturday, August 28, 2010

General Searching

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


In GeneralSearching.h

#include <iostream>
using namespace std;

class GeneralSearching
{
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 GSearching(int *arr, int target)
    {
        int flag = 0;
        int mid = N / 2;
        if (arr[mid] == target)
        {
            cout << "\nValue " << target << " found at index : " << mid + 1;
            flag = 1;
        }
        else if (arr[mid] < target)        //More than half of array
        {
            for (int k = mid + 1; k <= 10; ++k)
            {
                if (arr[k] == target)
                {
                    cout << "\nValue " << target << " found at index (from 1 to 11) : " << k + 1;
                    flag = 1;
                }
            }
        }
        else if (arr[mid] > target)        //Less than half of array
        {
            for (int k = mid - 1; k >= 0; --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 "GeneralSearching.h"
int main()
{
    GeneralSearching gs;

    for (int i = 0; i <= 10; ++i)
    {
        cout << "Enter values in array : " << i+1 << " of 11: ";
        cin >> gs.arr[i];
    }
    gs.BSort(gs.arr);
    cout << "\n\nAfter Bubble Sort input numbers are\n";
    for (int i = 0; i <= 10; ++i)
    {
        cout << gs.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;
        gs.GSearching(gs.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...!