C++ Example – Bubble Sort Algorithm




The bubble sort Algorithm simply compares adjacent elements and exchanges them if they are out of order.

To apply the Bubble Sort we follow the following steps.

  • Compare 1st two elements and exchange them if they are out of order.
  • Move down one element and compare 2nd and 3rd elements. Exchange if necessary. Continue until end of array.
  • Pass through array again, repeating process and exchanging as necessary.
  • Repeat until a pass is made with no exchanges.

Online computer science courses to jumpstart your future.
In this lesson we will learn how to write a source code in C++ programming language for doing simple bubble sort using array in ascending order.

#include <iostream>

void PrintArray(int *array, int n) {
  for (int i = 0; i < n; ++i)
    std::cout << array[i] << " " << std::flush;
  std::cout << std::endl;
}

void BubbleSort(int *array, int n) {
  bool swapped = true;
  int j = 0;
  int temp;

  while (swapped) {
    swapped = false;
    j++;
    for (int i = 0; i < n - j; ++i) {
      if (array[i] > array[i + 1]) {
        temp = array[i];
        array[i] = array[i + 1];
        array[i + 1] = temp;
        swapped = true;
      }
    }
  }
}

int main() {
  int array[] = {94, 42, 50, 95, 333, 65, 54, 456, 1, 1234};
  int n = sizeof(array)/sizeof(array[0]);

  std::cout << "Before Bubble Sort :" << std::endl;
  PrintArray(array, n);

  BubbleSort(array, n);

  std::cout << "After Bubble Sort :" << std::endl;
  PrintArray(array, n);
  return (0);
}


/*
OUTPUT
Before Bubble Sort :
94 42 50 95 333 65 54 456 1 2325
After Bubble Sort :
1 42 50 54 65 94 95 333 456 2325
*/

 


Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com





Be the first to comment

Leave a Reply

Your email address will not be published.


*