Bubble Sort in C++
Q. Write a C++ program for bubble sort.
#include <iostream>
using namespace std;
int main()
{
int a[100], n, i, j, temp;
cout << "Enter the number of elements: ";
cin >> n;
cout << "Enter the integers: ";
for (i = 0; i < n; i++)
{
cin >> a[i];
}
for (i = 0 ; i < n - 1; i++)
{
for (j = 0 ; j < n - i - 1; j++)
{
if (a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
cout << "Sorted array: ";
for (i = 0; i < n; i++)
{
cout << a[i] << " ";
}
return 0;
}
Q. Write an algorithm to bubble sort in C++.
1. Start
2. Read the integer `n` (number of elements).
3. Declare an array `a` of size `n`.
4. For `i` = 0 to `n-1`
- Read `a[i]`, the elements of the array.
5. For `i` = 0 to `n-2`
- For `j` = 0 to `n-i-2`
- If `a[j]` > `a[j+1]`
- Swap `a[j]` and `a[j+1]`.
6. Print the sorted array `a`.
7. End
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com