Bubble Sort
- C++
- Java
- Python
//Bubble Sort⏩ Repetedly swap two "adjacent" elements if they are in wrong order.
#include <iostream>
#include <vector>
#include <algorithm>
// #include <numeric>
using namespace std;
int main()
{
freopen("inputf.in", "r", stdin);
freopen("outputf.in", "w", stdout);
int n;
cin >> n;
vector<int> v(n);
//Assigning values to the vector
for (int i = 0; i < v.size(); i++) {
cin >> v.at(i);
}
//Bubble Sort Algorithm
int count = 1;
while (count < n) {
for (int i = 0; i < n - count; i++) {
if (v.at(i) > v.at(i + 1)) {
swap(v.at(i), v.at(i + 1)); //#include <algorithm>
//OR swap(v[i], v[i+1]);
//OR int temp = v.at(i);
// v.at(i)=v.at(j);
// v.at(j)=temp;
}
}
count++;
}
//another way of Bubble Sort
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (v.at(j) > v.at(j + 1)) {
swap(v.at(j), v.at(j+1));
}
}
}
//printing the Vector
for (auto el : v)
cout << el << " ";
//<==<==<==<==<==<==STL std::sort()⏩⏩⏩⏩⏩⏩
//also refer ⏩ http://www.cplusplus.com/reference/algorithm/sort/
//also refer ⏩ https://www.geeksforgeeks.org/sort-c-stl/
// sort(v.begin(), v.begin() + v.size());
// for (auto el : v)
// cout << el << " ";
return 0;
}
import java.util.*;
import java.io.*;
public class BubbleSort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// Bubble Sort
int count = 1;
while (count < n) {
for (int i = 0; i < n - count; i++) {
if (arr[i] > arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
count++;
}
for (var el : arr) {
System.out.print(el + " ");
}
sc.close();
}
}
def hello_world():
print 'Hello, world!'