//Author: Frank R. Mendez
//Title: Object Oriented Bubble Sort
//Description: Accepts an int array element to sort using bubblesort in ascending order

#include <iostream>
using namespace std;

class BubbleSort {
public:
    void bubble(int arr[], int size);
    void driver();
    void display();
    int arr[50];
    int array_size;
    int temp;

};

void BubbleSort::driver() {
    cout<<"Enter size of list:" << endl;
    cin>>array_size;
    cout<<"Enter " << array_size << " values" << endl;
    cout << endl;
    for(int b = 0; b <= array_size -1; b++) {
        cout << "Value [" << b << "]:";
        cin>>arr[b];
     }
     cout << "Elements of your unsorted list: [ ";
    for(int c = 0; c <= array_size -1; c++){
        cout << arr[c] << " " ;
    }
        cout << "]" << endl;
        display();
}



void BubbleSort::bubble(int arr[], int array_size) {
    for (int k = 0; k < array_size; k++)
        for (int i = 0; i < array_size -k -1; i++)
            if (arr[i] > arr[i +1]){
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
      }
}

void BubbleSort::display() {

    bubble(arr,array_size);
        cout << "Elements of your sorted list: [ ";
        for(int x = 0; x < array_size; x++) {
            cout << arr[x] << " ";
        }
        cout << "]";
}

int main () {
    BubbleSort frank;
    frank.driver();
    return 0;
}

Recommended Answers

All 3 Replies

Ignoring for the moment that this is a horrible example of object orientation and brings into question whether you're qualified to be giving out examples as if you know what you're doing, what exactly is the benefit of an object oriented bubble sort here?

commented: Succinctly put D. :-) +12

I prefer my Generic Programming (GP) version of bubble-sort:

template <typename ForwardIter, typename Compare>
void bubble_sort(ForwardIter first, ForwardIter last, Compare comp) {
  ForwardIter current_next;
  for(bool swapped = true; (swapped && (!(swapped = false))); --last) 
    for(ForwardIter current = first; (current_next = std::next(current)) != last; ++current) 
      if ( comp(*current_next, *current) && ( swapped = true ) ) 
        std::iter_swap(current, current_next); 
};

(warning: submitting this for a homework is going to draw a lot of suspicion)

commented: I like the warning +11
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.