Welcome, guest! Login / Register - Why register?
Psst.. new poll here.
Psst.. new forums here.
Microsoft is blocking us again (TY IP Reputation!) so just use oauth login instead. :)

Paste

Pasted as C++ by Xagar ( 4 years ago )
#include <iostream>

using namespace std;

class SortTester {
  public:
    int size;
    int array[10] = {12,23,32,122,2,56,34,5,66,89};
//Declaring constructor and initialisng size inside it.
  SortTester(int s) {
    size = s;
  }
  
//Returns true if the 1st parameter is greater than second.
  bool compare(int x, int y){
      if(x>y) return true ;
      else return false;
  }
  
//Takes the indices of array and swaps the item of those indices.
  void swap(int x, int y){
      int temp = array[x];
      array[x] = array[y];
      array[y] = temp;
  }
  
//Prints the array's entire element.
  void print(){
      cout << '[';
      for(int i = 0; i < size ; i++){
          cout << array[i];
          if(i != size -1){
              cout << ",";
          }
      }
      cout << ']';
  }
  
};

//This function will perform bubble sort from left or right side depending upon passNum and returns true if no any change is made in the array..
bool singleBubblePass(SortTester& tester, unsigned int size, unsigned int passNum) {
  bool sorted = true;

//For even passNum, shifting the smallest element to left side.
  if(passNum % 2 == 0){
       for(int i = size-1; i > 0; i--){
        if( tester.compare(tester.array[i],tester.array[i-1]) == false ){
            tester.swap(i , i-1);
            sorted = false;
        }
    }  
  }
  
//For odd passNum, shifting the largest element to right side.
  else{
    for(int i = 0; i < size -1; i++){
        if(tester.compare(tester.array[i],tester.array[i+1]) == true ){
            tester.swap(i , i+1);
            sorted = false;
        }
    }  
  }
  return sorted;
}

int main() {
  unsigned int size = 10;
  SortTester tester = SortTester(10);
  cout << "Unsorted" << endl;
     tester.print();
  bool sorted = false;
  unsigned int numPasses = 0;
  while (not sorted) {
    sorted = true;
    numPasses++;
    sorted = singleBubblePass(tester, 10, numPasses);
  }
 cout << endl << endl;
 cout << "Sorted" << endl;
 tester.print();
}

 

Revise this Paste

Your Name: Code Language: