Bubble Sort is a simple algorithm which is used to sort a given set of n
elements provided in form of an array with n
number of elements. Bubble Sort compares all the element one by one and sort them based on their values.
If the given array has to be sorted in ascending order, then bubble sort will start by comparing the first element of the array with the second element, if the first element is greater than the second element, it will swap both the elements, and then move on to compare the second and the third element, and so on.
If we have total n
elements, then we need to repeat this process for n-1
times.
It is known as bubble sort, because with every complete iteration the largest element in the given array, bubbles up towards the last place or the highest index, just like a water bubble rises up to the water surface.
Sorting takes place by stepping through all the elements one-by-one and comparing it with the adjacent element and swapping them if required.
Program:
#include <iostream>
using namespace std;
void swap (int arr[], int i, int j) //function for swaping
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
void bubbleSort (int arr[], int n) //function for sorting
{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
swap (arr, j, j + 1); //swap function call
}
}
}
int main ()
{
int arr[] = { 6, 2, 5, 3, 9 };
int n = sizeof (arr) / sizeof (arr[0]);//getting size of array and storing it in variable n
bubbleSort (arr, n); //function call
cout << "Sorted array:" << endl;
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Output:
Sorted array:
2 3 5 6 9
No comments: