arr = [12,1,6,23,234,456,2,35,687,34]
# arry consists of 9 elements
n = len(arr)
#conts the element of the arry
for j in range(n-1): #this is for list to get shorted properly && you dont need to go full as it may take more steps to exicute
for i in range(n-j-1): #if left with n the there will be array error because it will try to add 1 to n in below leading to array being bigger
if arr[i]>arr[i+1]:
arr[i],arr[i+1]=arr[i+1],arr[i]
else:
pass
# arry starts from last and eventually decrease the number lower and lower which leads to lesser steps
# #above took 125 steps to eully exicute
#################################################################
# #this takes 217 steps to run and end code
# for i in range(n):
# if arr[i]>arr[i+1]:
# arr[i],arr[i+1]=arr[i+1],arr[i]
# else:
# pass
#################################################################
print("the sorted array is : "arr)
// C program for implementation of Bubble sort
#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("
");
}
// Driver program to test above functions
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array:
");
printArray(arr, n);
return 0;
}
"""Bubblesort
"""
## Un-optimised--------------------------------------------------------------
def bubble_1(lst):
n = len(lst) - 1
for i in range(n):
# Within the unsorted portion
for j in range(n - i):
# If curr > next, swap
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
return lst # for easy testing
def bubble_2(lst):
n = len(lst) - 1
# Within the unsorted portion, except the last number
for unsorted in range(n, 0, -1):
for i in range(unsorted):
# If curr > next, swap
if lst[i] > lst[i+1]:
lst[i], lst[i+1] = lst[i+1], lst[i]
return lst # for easy testing
## Optimised-----------------------------------------------------------------
def bubble_3(lst):
n = len(lst) - 1
# Within the unsorted portion, except the last number
for unsorted in range(n, 0, -1):
swapped = False
for i in range(unsorted):
# If curr > next, swap
if lst[i] > lst[i+1]:
lst[i], lst[i+1] = lst[i+1], lst[i]
swapped = True
# Check if its sorted by this time
if not swapped:
break
return lst # for easy testing
import java.util.Arrays;
public class Bubble{
public static void main(String[] args){
int[] arr = {5,4,3,2,1}; // Test case array
for(int i =0;i<arr.length-1;i++){ // Outer Loop
boolean swap = false;
for(int j =1;j<arr.length;j++){ // Inner Loop
if(arr[j-1]>arr[j]){ // Swapping
int temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
swap = true;
}
}
if(!swap){ // If you went through the whole arrray ones and
break; // the elements did not swap it means the array is sorted hence stop
}
}
System.out.print(Arrays.toString(arr));
}
}
Bubble sort, aka sinking sort is a basic algorithm
for arranging a string of numbers or other elements
in the correct order. This sorting algorithm is
comparison-based algorithm in which each pair of
adjacent elements is compared and the elements are
swapped if they are not in order. The algorithm then
repeats this process until it can run through the
entire string or other elements and find no two
elements that need to be swapped. This algorithm is
not suitable for large data sets as its average and
worst case complexity are of Ο(n2) where n is the number of items.
In general, Just like the movement of air bubbles
in the water that rise up to the surface, each element
of the array move to the end in each iteration.
Therefore, it is called a bubble sort.
// Go impelementation of Bubble Sort
package main
import "fmt"
func bubbleSort(arr []int) {
// Finding the length of the array
n := len(arr)
for i := 0; i < n; i++ {
for j := 0; j < n-i-1; j++ {
// if the fist lement is greater than the second one then swap
if arr[j] > arr[j+1] {
arr[j], arr[j+1] = arr[j+1], arr[j]
}
}
}
}
func printArray(arr []int) {
n := len(arr)
for i := 0; i < n; i++ {
fmt.Print(arr[i], " ")
}
fmt.Println()
}
func main() {
arr := []int{24,35,8,16,64}
bubbleSort(arr)
printArray(arr)
}
// Bubble Sort algorithm -> jump to line 21
...
#include <iostream> // Necessary for input output functionality
#include <bits/stdc++.h> // To simplify swapping process
...
...
/**
* Sort array of integers with Bubble Sort Algorithm
*
* @param arr Array, which we should sort using this function
* @param arrSZ The size of the array
* @param order In which order array should be sort
*
* @return Sorted array of integers
*/
void bubbleSortInt(double arr[], int arrSz, string order = "ascending")
{
for (int i = 0; i < arrSz; ++i)
{
for (int j = 0; j < (arrSz - i - 1); ++j)
{
// Swapping process
if ((order == "descending") ? arr[j] < arr[j + 1] : arr[j] > arr[j + 1])
{
swap(arr[j], arr[j + 1]);
}
}
}
return; // Optional because it's a void function
} // end bubbleSortInt
...
int main()
{
...
return 0; // The program executed successfully.
} // end main
#include<bits/stdc++.h>
#define swap(x,y) { x = x + y; y = x - y; x = x - y; }
using namespace std;
/**
* Function to Sort the array using Modified Bubble Sort Algorithm
* @param arr: Array to be Sorted
* @param n: Size of array
* @return : None
*/
void bubbleSort(int arr[], int n)
{
int i, j;
bool flag;
// Outer pass
for(i = 0; i < n; i++)
{
flag = false; // Set flag as false
for(j = 0; j < n-i-1; j++)
{
// Compare values
if( arr[j] > arr[j+1])
{
swap(arr[j],arr[j+1]);
flag = true;
}
}
// If no to elements are swapped then
// array is sorted. Hence Break the loop.
if(!flag)
{
break;
}
}
}
int main(int argv, char* argc[])
{
int arr[] = {1,5,6,8,3,4,7,2,9};
int n = sizeof(arr)/sizeof(int);
cout<<"Unsorted Array :";
for(int i=0;i<n;i++) // Print the Original Array
cout<<arr[i]<<" ";
cout<<endl;
bubbleSort(arr,n); // Call for Bubble Sort Function
cout<<"Sorted Array :";
for(int i=0;i<n;i++) // Print the Sorted Array
cout<<arr[i]<<" ";
return(0);
}
const bubbleSort = (arr) => {
let sorted = false;
while (!sorted) {
sorted = true;
for (let i = 0; i < arr.length - 1; i++) {
// compare arr[i] to arr[i+1]
// swap places if needed
// if swapped, set sorted = false to run while loop again
}
}
return arr;
};
bubbleSort(array)
swapped <- false
for i <- 1 to indexOfLastUnsortedElement-1
if leftElement > rightElement
swap leftElement and rightElement
swapped <- true
end bubbleSort
Void bubbleSort(int arr[ ], int n){
For( int I = 0; I < n-1; I++){ //outer loop for iterating to n-1 elements
For( int j = 0; j < n-I-1; j++){ //inner loop for checking each element
If (arr[ j ] > arr[ j+1 ]{ // For swapping if previous element is greater than next one
Swap( arr[ j ], arr[ j+1 ]);
}
}
}
}
function bubbleSort(arr) {
// This variable is used to either continue or stop the loop
let continueSorting = true;
// while continueSorting is true
while (continueSorting) {
// setting continueSorting false. below check to see if swap,
// if a swap,continue sorting. If no swaps, done sorting,
// and stop our while loop.
continueSorting = false;
// loop through the arr from 0 to next to last
for (let i = 0; i < arr.length - 1; i++) {
// check if we need to swap
if (arr[i] > arr[i + 1]) {
// swap
let temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
// since a swap was made, we want to continue sorting
continueSorting = true;
}
}
}
// After all swaps have been made, then we return our sorted array
return arr;