# Bubble Sort in C++

### What is Bubble Sort ?

• Compares consecutive items and if they’re out of place we will swap them. The highest number will bubble its way to the right with each iteration

• A sorted partition will form at the end of the array

### Code (in C++)

``````#include <iostream>

using std::cout; using std::endl;

void swap(int *xpoint, int *ypoint)
{   // Swap the int
int temp = *xpoint;
*xpoint = *ypoint;
*ypoint = temp;
}

void BubbleSort(int arr[], int size)
{
for (int i = 0; i < size-1; i++)
{
for (int j = 0; j < size-i-1; j++) {

if (arr[j] > arr[j+1]) {
// Send two int to swap function
swap(&arr[j], &arr[j+1]);

}
}
}
}

void PrintArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}

int main()
{
int arr[] = {2, 8, 5, 3, 9, 4, 1};
int size = sizeof(arr)/sizeof(arr);
cout << "Array before being sorted: ";
PrintArray(arr, size);
BubbleSort(arr, size);
cout<<"Sorted array using Bubble Sort: ";
PrintArray(arr, size);

}
``````

Output:

``````Array before being sorted: 64 34 25 12 22 11 90
Sorted array using Bubble Sort: 11 12 22 25 34 64 90
``````

#### Notes on Bubble Sort   