dev-resources.site
for different kinds of informations.
Bubble Sort
Published at
6/27/2023
Categories
bubblesort
sort
cpp
sorting
Author
Ankit Kumar Meena
Main Article
Bubble Sort:
It is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order.
In this algorithm,
- Traverse from left and compare adjacent elements and the higher one is placed at right side.
- In this way, the largest element is moved to the rightmost end at first.
- This process is then continued to find the second largest and place it and so on until the data is sorted.
C++ Code
#include <bits/stdc++.h>
using namespace std;
void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped;
for (i = 0; i < n - 1; i++) {
swapped = false;
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
swapped = true;
}
}
if (swapped == false)
break;
}
}
void print(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << " " << arr[i];
}
int main()
{
int arr[] = { 23, 45, 65, 23, 57, 88 };
int N = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, N);
cout << "Sorted array: \n";
print(arr, N);
return 0;
}
Time Complexity: O(N2)
Auxiliary Space: O(1)
Articles
12 articles in total
Getting Started with Docker: A Guide for Developers
read article
Mastering Fragments in Java for Android Development
read article
Mastering RecyclerView in Java for Android Development
read article
Understanding Adapters in Java for Android Development
read article
My Journey in Android Development: Learning Java and Building Apps
read article
Merge Sort
read article
Selection Sort
read article
Bubble Sort
currently reading
Insertion Sort
read article
The Artistry of Front-End Development: Building Captivating User Experiences
read article
Demystifying Cloud Computing: A Comprehensive Guide
read article
Hi!
read article
Featured ones: