Stw59
Stw59

Reputation: 21

Bubble Sort not working correctly

I've been working on this for awhile and I have tried multiple different algorithms for the bubble sort that I have found online but none of them are working properly for me and I'm pretty close to giving up, but this is due tomorrow night. I'd really appreciate if someone could point out where im going wrong. I dont really understand this algorithm with the bool so ill try to find what i was trying before and edit it in

#include <iostream>
using namespace std;

void GetInfo(int[], int&);
void BubbleSort(int[], int);
void BinarySearch(int[], int);

int main()
{
    int size;
    int array[500];
    GetInfo(array, size);
    BubbleSort(array, size);
    BinarySearch(array, size);
    return 0;
}

void GetInfo(int array[], int& size)
{
    cout << "Enter the number of naturals: ";
    cin >> size;
    cout << "Enter the natural numbers to sort: ";
    for (int i = 0; i < size; i++)
    {
        cin >> array[i];
    }

}

void BubbleSort(int array[], int size)
{
    int temp;
    bool check = true;
    int end = 0;
    while(check)
    {
        end++;
        check = false;

        for(int i = 0; i < size - end; i++)
        {
            if (array[i] > array[i+1]) //I'm positive this part is correct
            {
                temp = array[i];
                array[i] = array[i+1];
                array[i+1] = temp;
                check = true;
            }
        }

    }
       cout << endl << "Numbers sorted in ascending order: " << endl;
    for (int i = 0; i < size; i++)
    {
        cout << array[i] << ' ';
    }
}

void BinarySearch(int array[], int size) //this doesnt work properly atm but 
{                                        //should be good when the sort works
    int index;
    int top = size - 1;
    int bottom = 0;
    int middle = (top) / 2;
    bool found = false;
    int target;

    cout << endl << "Enter the number to search: ";

    cin >> target;

    while (found == false)
    {
        if (target > array[middle])
        {
            bottom = middle + 1 ;
            middle = ((top - bottom)/2) + bottom;
        }
        else if (target < array[middle])
        {
            top = middle - 1;
            middle = ((top - bottom)/2) + bottom;
        }
        else
        {
            found = true;
            index = middle;
        }
    }
    cout << "Number " << target << " is found in position " << index << endl;
}

Upvotes: 1

Views: 285

Answers (2)

R Sahu
R Sahu

Reputation: 206737

These lines are wrong:

            array[i] = array[size+1];
            array[size+1] = temp;

You need:

            array[i] = array[i+1];
            array[i+1] = temp;

Upvotes: 1

miushock
miushock

Reputation: 1097

You might meant to swap a[i] with a[i+1] while you actually swapped a[size+1]

Upvotes: 1

Related Questions