I built this entire program and it does what I want it to except I want to use a bubble sort algorithm instead of the

std::sort()

function I have right now.

So please help me out on this. I don't really understand how bubble sorts work even after reading up on it.

Just a simple example of a bubble sort will do! Thanks!!! ;)

Here is my code with the std::sort().

:)

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
 
	int SIZE ; // Array size variable.
	int i ;
	int n = 0 ;
	int n2 = 0 ;

int main() // Start program execution.
{
	
		vector < int > Vector ( SIZE ) ; // Vector array declaration.

		cout << "Please insert array size: " ; // Prompt user for array SIZE variable input.
		cin >> SIZE ; // Get user chosen variable SIZE and store to variable int SIZE.

		cout << "Welcome to Array [" << SIZE <<"]." << endl ; // Print welcome note and SIZE of array.
		cout << endl ; //Prints blank line

		cout << "Unsorted below... " << endl ;

		for( i = 0; i < SIZE; i++ ) 
		{
			cout << "Array[" << n++ << "]: " ; // Print array name and element number
			Vector.push_back( rand() ) ; // Add random number inside each of the elements required
			cout << Vector.at(i) << endl ; // Print the random number added
		}

		cout << endl ; // Prints blank line
		cout << "Sorted below..." << endl ;
	
		for( i = 0; i < SIZE; i++ ) 
		{
			std::sort( Vector.begin(), Vector.end() ) ; // Sorts numbers from smallest to largest
			cout << "Array[" << n2++ << "]: " ; // Print array name and element number
			cout << Vector.at(i) << endl ; // Print the random number sorted
		}
	
	return 0; //Indicate successful termination.
}

This one is pretty simple :

void bubbleSort(vector<int>& vec, bool sortAccendingOrder = true){

	for(int i = 0; i < vec.size();i++)
		for(int j = i+1; j < vec.size(); j++)
		{
			if(sortAccendingOrder)
			{
				if(vec[i] > vec[j])
					std::swap(vec[i],vec[j]);
			}

			else if(vec[i] < vec[j]) //else decendingOrder
				std::swap(vec[i],vec[j]);
		}
			
}
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.