C++ Program for Bubble Sort

C++ program for bubble sort algorithm is provided on this page.

Bubble sort is a sorting algorithm that repeatedly steps throught the list and compares adjacent elements and swaps them if they are in wrong order.

This sorting algorithm is simple and most commonly used algorithm.

To learn more about this check out this article on bubble sort.

C++ program for bubble sort

Following c++ program uses bubble sort algorithms to sort and array of numbers in ascending order.

You can convert this program to sort the array in descending order by simple changing comparision operator.

This will be good exercise for you, if you find out yourself where to change the sign.

/* Implement Bubble sort on an array in c++ */

#include<iostream>
using namespace std;

void BubbleSort (int arr[], int size);

int main()
{
 int i, size;

 cout << endl << "Enter the number array elements: ";
 cin >> size;
 
 int arr[size];

 for(i = 0; i < size; i++)
 {
  cout << "Enter array element: " << i+1 << ": ";
  cin >> arr[i];
 }
 
 BubbleSort(arr, size);

 cout << endl << "Sorted Array: ";
 for (i = 0; i < size; i++)
        cout << " " << arr[i];
 
 return 0;
}

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

Output:

Enter number of array elements: 5
Enter array element no 1: 20
Enter array element no 2: 30
Enter array element no 3: 10
Enter array element no 4: 40
Enter array element no 5: 50

Sorted Array:  10 20 30 40 50

Comments