An algorithm to sort an array using Bubble Sort.

###An algorithm to sort an array using Bubble Sort.(Bubble Sort Algorithm).
Flowchart given below:


Now we will implement this algorithm in a program.

Source Code In C++:
#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
  int i,j,k,a[1000],count,temp;
  std::cout << "How many elements: ";
  std::cin >>count;
  for (size_t i = 0; i < count; i++) {
      std::cin >> a[i];
  }
  for (size_t i = 0; i < count-1; i++) {
    for (size_t j = 0; j <= count-2-i; j++) {
      if (a[j]>a[j+1]) {
        temp=a[j];
        a[j]=a[j+1];
        a[j+1]=temp;
      }
    }
  }
  std::cout << "After Sorting: " << '\n';
  for (size_t i = 0; i < count; i++) {
    std::cout << a[i] << '\n';
  }
  return 0;
}
 

Output:
How many elements: 5
6
3
5
1
2
After Sorting:
1
2
3
5
6

Press any key to continue . . .

Explanation:

Here we were asked for to sort an unsorted array using bubble sort algorithm.In bubble sort,we just compare two elements at a time and then we store the biggest number after the shortest number.















This is how we can sort an array using bubble sort.
 










No comments

Powered by Blogger.