C++ Program to Implement Bubble Sort on an Array

Write a c++ program to implement bubble sort on array elements. Write a c++ program to sort array elements using bubble sort.

C++ program to implement bubble sort Onan array

/* 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