arr =[12,1,6,23,234,456,2,35,687,34]#arryconsists of 9 elements
n =len(arr)#contsthe 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
#arrystarts 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
#fori in range(n):#ifarr[i]>arr[i+1]:#arr[i],arr[i+1]=arr[i+1],arr[i]#else:#pass
#################################################################
print("the sorted array is : "arr)
public class BubbleSortExample {staticvoidbubbleSort(int[] arr){int n = arr.length;int temp =0;for(int i=0; i < n; i++){for(int j=1; j <(n-i); j++){if(arr[j-1]> arr[j]){//swap elements
temp = arr[j-1];
arr[j-1]= arr[j];
arr[j]= temp;}}}}
public staticvoidmain(String[] args){int arr[]={3,60,35,2,45,320,5};
System.out.println("Array Before Bubble Sort");for(int i=0; i < arr.length; i++){
System.out.print(arr[i]+" ");}
System.out.println();bubbleSort(arr);//sorting array elements using bubble sort
System.out.println("Array After Bubble Sort");for(int i=0; i < arr.length; i++){
System.out.print(arr[i]+" ");}}}
def bubble_sort(nums):
n =len(nums)for i in range(n):
swapped = False
for j in range(1, n - i):if nums[j]< nums[j -1]:
nums[j], nums[j -1]= nums[j -1], nums[j]
swapped = True
if not swapped:breakreturn nums
print(bubble_sort([9,8,7,6,5,4,3,2,1]))
// C program for implementation of Bubble sort#include<stdio.h>voidswap(int*xp,int*yp){int temp =*xp;*xp =*yp;*yp = temp;}// A function to implement bubble sortvoidbubbleSort(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 */voidprintArray(int arr[],int size){int i;for(i=0; i < size; i++)printf("%d ", arr[i]);printf("
");}// Driver program to test above functionsintmain(){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);return0;}
"""Bubblesort
"""
## Un-optimised--------------------------------------------------------------
def bubble_1(lst):
n =len(lst)-1for i in range(n):#Within the unsorted portionfor j in range(n - i):#If curr > next, swapif 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 numberfor unsorted in range(n,0,-1):for i in range(unsorted):#If curr > next, swapif 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 numberfor unsorted in range(n,0,-1):
swapped = False
for i in range(unsorted):#If curr > next, swapif lst[i]> lst[i+1]:
lst[i], lst[i+1]= lst[i+1], lst[i]
swapped = True
#Check if its sorted by this timeif not swapped:breakreturn lst # for easy testing
public class BubbleSortExample {staticvoidbubbleSort(int[] arr){int n = arr.length;int temp =0;for(int i=0; i < n; i++){for(int j=1; j <(n-i); j++){if(arr[j-1]> arr[j]){//swap elements
temp = arr[j-1];
arr[j-1]= arr[j];
arr[j]= temp;}}}}
public staticvoidmain(String[] args){int arr[]={3,60,35,2,45,320,5};
System.out.println("Array Before Bubble Sort");for(int i=0; i < arr.length; i++){
System.out.print(arr[i]+" ");}
System.out.println();bubbleSort(arr);//sorting array elements using bubble sort
System.out.println("Array After Bubble Sort");for(int i=0; i < arr.length; i++){
System.out.print(arr[i]+" ");}}}
import java.util.Arrays;
public class Bubble{
public staticvoidmain(String[] args){int[] arr ={5,4,3,2,1};// Test case arrayfor(int i =0;i<arr.length-1;i++){// Outer Loop
boolean swap = false;for(int j =1;j<arr.length;j++){// Inner Loopif(arr[j-1]>arr[j]){// Swappingint 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 swapif 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
*/voidbubbleSortInt(double arr[],int arrSz, string order ="ascending"){for(int i =0; i < arrSz;++i){for(int j =0; j <(arrSz - i -1);++j){// Swapping processif((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...intmain(){...return0;// The program executed successfully.}// end main
#include<bits/stdc++.h>#defineswap(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
*/voidbubbleSort(int arr[],int n){int i, j;
bool flag;// Outer passfor(i =0; i < n; i++){
flag = false;// Set flag as falsefor(j =0; j < n-i-1; j++){// Compare valuesif( 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;}}}intmain(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-1if 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 elementsFor(int j =0; j < n-I-1; j++){//inner loop for checking each elementIf(arr[ j ]> arr[ j+1]{// For swapping if previous element is greater than next oneSwap( 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 truewhile(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 lastfor(let i =0; i < arr.length -1; i++){// check if we need to swapif(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 arrayreturn arr;