Bubble Sort

When it comes to sorting algorithms, Bubble Sort is usually the first that comes to mind. Though it might not be the fastest tool in the shed, it's definitely straightforward to implement and is often the first sorting method new programmers think of when trying to implement a sorting method on their own.

Here's how it works: we go through each element in our vector and check to see if it is larger than the element to it's right. If it is, we swap the elements and then move to the next element. In this way, we sweep through the array times for each element and continually swap any two adjacent elements that are improperly ordered. This means that we need to go through the vector times with code similar to the following:

function bubble_sort!(a::Vector{Float64})
    n = length(a)
    for i = 1:n
        for j = 1:n-1
            if(a[j] < a[j+1])
                a[j], a[j+1] = a[j+1], a[j]
            end
        end
    end
end
public static List<T> RunBubbleSort<T>(List<T> list) where T : IComparable<T>
{
    var length = list.Count;

    for (int i = 0; i < length; i++)
    {
        for (int j = 1; j < length; j++)
        {
            if (list[j - 1].CompareTo(list[j]) > 0)
            {
                var temp = list[j - 1];
                list[j - 1] = list[j];
                list[j] = temp;
            }
        }
    }

    return list;
}
void bubble_sort(int *array, size_t n) {
    for (size_t i = 0; i < n; ++i) {
        for (size_t j = 0; j < n - 1; ++j) {
            if (array[j] > array[j + 1]) {
                int tmp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = tmp;
            }
        }
    }
}
static void bubbleSort(int[] arr) {
    for (int r = arr.length - 1; r > 0; r--) {
        for (int i = 0; i < r; i++) {
            if(arr[i] > arr[i + 1]) {
                int tmp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = tmp;
            }
        }
    }
}
fun bubbleSort(input: MutableList<Int>) {
    for (i in (input.size - 1) downTo 0) {
        for (j in 0 until i) {
            if (input[j] > input[j + 1]) {
                input[j] = input[j + 1].also {
                    input[j + 1] = input[j]
                }
            }
        }
    }
}
function bubbleSort(arr) {
  let tmp;
  for (let i = 0; i < arr.length; i++) {
    for (let k = 0; k < arr.length - 1; k++) {
      if (arr[k] > arr[k + 1]) {
        tmp = arr[k];
        arr[k] = arr[k + 1];
        arr[k + 1] = tmp;
      }
    }
  }
}
def bubble_sort(array):
    len_array = len(array)
    for i in range(len_array):
        for j in range(len_array - i - 1):
            if(array[j] > array[j+1]):
                array[j], array[j+1] = array[j+1], array[j] #swap elements in the list
function sorted_array = bubblesort(array)
    for i = 1 : length(array)
        for j = 1 : length(array) - i
            if array(j) > array(j+1)
                % swap elements in the list
                temp       = array(j);
                array(j)   = array(j+1);
                array(j+1) = temp;
            end
        end
    end
    sorted_array = array;
end
function bubble_sort(arr)
  for i = 1,#arr-1 do
    for j = 1,#arr-1 do
      if arr[j] > arr[j+1] then
        arr[j], arr[j+1] = arr[j+1], arr[j]
      end
    end
  end
end
bubbleSort :: (Ord a) => [a] -> [a]
bubbleSort x = (!!length x) $ iterate bubble x
  where bubble (x:y:r)
          | x <= y    = x : bubble (y:r)
          | otherwise = y : bubble (x:r)
        bubble x = x
template <class Iter>
void bubble_sort(Iter first, Iter last) {
  for (auto it1 = first; it1 != last; ++it1) {
    for (auto it2 = first; it2 + 1 != last; ++it2) {
      // these are unsorted! gotta swap 'em
      if (*(it2 + 1) < *it2) {
        std::iter_swap(it2, it2 + 1);
      }
    }
  }
}
fn bubble_sort(a: &mut [u32]) {
    let n = a.len();

    for _ in 0..n {
        for j in 1..n {
            if a[j - 1] > a[j] {
                a.swap(j, j - 1);
            }
        }
    }
}
void bubbleSort(R)(ref R range)
if (isRandomAccessRange!R && hasAssignableElements!R && hasLength!R)
{
    import std.algorithm : swap;

    foreach (i; 0 .. range.length) {
        bool isSorted = true;
        foreach (j; 0 .. range.length - 1)
            if (range[j + 1] < range[j]) {
                swap(range[j + 1], range[j]);
                isSorted = false;
            }
        if (isSorted)
            return;
    }
}
func bubbleSort(array []int) {
    n := len(array)
    for i := 0; i < n-1; i++ {
        swapped := false
        for j := 0; j < n-i-1; j++ {
            if array[j] > array[j+1] {
                array[j], array[j+1] = array[j+1], array[j]
                swapped = true
            }
        }
        if !swapped {
            break
        }
    }
}
(define bubbleSort
  (case-lambda [(l) (bubbleSort l (length l))]
               [(l n) (if (= n 1)
                          l
                          (bubbleSort (pass l 0 n) (- n 1)))]))

; a single pass, if this is the nth pass, then we know that the (n - 1) last elements are already sorted
(define (pass l counter n)
  (let ([x (first l)]
        [y (second l)]
        [r (drop l 2)])
    (cond [(= (- n counter) 2) (cons (min x y) (cons (max x y) r))]
          [(cons (min x y) (pass  (cons (max x y) r) (+ counter 1) n))])))
func bubbleSort(sortArray: inout [Int]) -> [Int] {
    for i in (1..<sortArray.count).reversed() {
        for j in 0..<i {
            if sortArray[j] > sortArray[j+1] {
                let temp = sortArray[j]
                sortArray[j] = sortArray[j + 1]
                sortArray[j + 1] = temp
            }
        }
    }

    return sortArray
}
:"L IS LENGTH OF LIST"
:dim(L1)→L
:For(A,1,L)
:For(X,1,L-1)
:If L1(X)>L1(X+1)
:Then
:L1(X)→Y
:L1(X+1)→L1(X)
:Y→L1(X+1)
:End
:End
:End
def bubble_sort(arr)
    (0..arr.length - 1).each do
        (0..arr.length - 2).each do |k|
            if arr[k] > arr[k + 1]
                arr[k + 1], arr[k] = arr[k], arr[k + 1]
            end
        end
    end

    return arr
end
def bubble_sort(arr)
  arr = arr.dup 
  (0 ... arr.size).each do 
    (0 ... arr.size-1).each do |k| 
      if arr[k] > arr[k+1]
        arr[k+1],arr[k] = arr[k],arr[k+1]
      end
    end
  end 
  arr
end
function bubble_sort(array $arr): array
{
    for ($i = 0, $length = count($arr); $i < $length; $i++) {
        for ($j = 1; $j < $length; $j++) {
            if ($arr[$j - 1] > $arr[$j]) {
                $tmp = $arr[$j - 1];
                $arr[$j - 1] = $arr[$j];
                $arr[$j] = $tmp;
            }
        }
    }

    return $arr;
}
(defun bubble-up (list)
  (if
    (< (length list) 2) 
    list  
    (if 
      (> (first list) (second list))
      (cons 
        (second list) 
        (bubble-up 
          (cons 
            (first list) 
            (rest (rest list)))))           
      (cons 
        (first list)
        (bubble-up
          (rest list))))))

(defun bubble-sort (list)
  (if 
    (< (length list) 2)
    list
    (let* ((new-list (bubble-up list)))
      (append 
        (bubble-sort (butlast new-list)) 
        (last new-list)))))
proc bubble_sort(a: var openArray[int]) =
  for i in 0 .. < len(a) - 1:
    for j in 0 .. < len(a) - 1:
      if a[j + 1] < a[j]:
        swap(a[j], a[j + 1])
SequenceableCollection>>bubbleSort
    "Bubble sort for a collection."
    | len swapper thisElem nextElem |
    len  := self size.
    1 to: len - 1 do:  [ :iteration |
        1 to: len - 1 do: [ :index |
            thisElem := self at: index.
            nextElem := self at: index + 1.
            (thisElem > nextElem) ifTrue: [ 
                self at: thisIndex + 1 put: thisElem.
                self at: thisIndex put: nextElem.
            ]
        ]
    ]
bubble_sort:
  xor    rcx, rcx                 # The outer loop counter
  lea    rdx, [rdi + 4*rsi - 4]   # The end address for the inner loop

outer_loop:
  cmp    rcx, rsi                 # We first check if the outer loop is done
  jge    bubble_sort_done         # And if it is, return
  mov    rax, rdi                 # Otherwise we initialize the loop variable of the inner loop
inner_loop:
  mov    r8d, DWORD PTR [rax]     # Load array[j] and array[j+1] through a pointer
  mov    r9d, DWORD PTR [rax + 4]
  cmp    r8d, r9d                 # If array[j] <= array[j+1]
  jle    loop_counters            # Then we can skip this iteration
  mov    DWORD PTR [rax], r9d     # Otherwise swap the values
  mov    DWORD PTR [rax + 4], r8d
loop_counters:
  lea    rax, [rax + 4]           # First, advance the inner loop
  cmp    rax, rdx
  jl     inner_loop               # And in case it's not done, repeat
  inc    rcx                      # If it is done, go back to doing the outer loop
  jmp    outer_loop

bubble_sort_done:
  ret
SUBROUTINE bubblesort(array)

    IMPLICIT NONE
    INTEGER                              :: array_length, i, j, n
    REAL(8)                              :: tmp
    REAL(8), DIMENSION(:), INTENT(INOUT) :: array

    array_length = size(array)
    n = array_length

    DO i=1, n
        DO j=1, n-1
            IF ( array(j) > array(j+1) ) THEN

                tmp        = array(j+1)
                array(j+1) = array(j)
                array(j)   = tmp

            END IF
        END DO
    END DO
END SUBROUTINE bubblesort
set loop marker to 1 and starts loop
+
[

delete loop marker
-<<<<<

if there is a number here
[

add it to the empty space to the right 
and subtract it from the next number
[->+>-<<]

undo subtraction once without a zero check in case the numbers are equal
+>>+<-

then as long as the left number is bigger than zero
[<+>>

if the number to the right becomes a zero in the process 
due to buffer overflow set a swap marker
[<<<]<<[<<<<<+>>]

otherwise continue resetting numbers
>>>>>+<-]

set a "correct" marker between numbers
+

check swap marker
<<<<<<

if swap marker is set delete "correct" marker
[->>>>>>->

and swap the numbers
[-<+>]<<[->>+<<]>[-<+>]

go to next pair
<<<<<<]>>>

repeat until end of array
]

go to leftmost "correct" marker
>>>
def bubbleDown(list: List[Int]): List[Int] =
  list match {
    case a :: b :: tail if a < b => b :: bubbleDown(a :: tail)
    case a :: b :: tail => a :: bubbleDown(b :: tail)
    case _ => list
  }

def bubbleSort(list: List[Int]): List[Int] =
  bubbleDown(list) match {
    case unsorted :+ smallest => smallest :: bubbleDown(unsorted)
    case _ => list
  }
🐇 ❗️ 🛁 numbers 🍨🐚💯🍆 🍇
  🐔 numbers❗️ ➡️ count

  🔂 i 🆕⏩⏩ 0 count❗️ 🍇
    🔂 j 🆕⏩⏩ 1 count❗️ 🍇
      ↪️ 🐽 numbers j ➖  1❗️ ▶️ 🐽 numbers j❗️ 🍇
        🐽 numbers j ➖ 1❗️ ➡️ temp
        🐷 numbers j ➖ 1 🐽 numbers j❗️❗️
        🐷 numbers j temp❗️
      🍉
    🍉
  🍉
🍉
bubble_sort() {
    local i
    local j
    local tmp
    local len
    local arr
    arr=("[email protected]")
    (( len = ${#arr[@]} ))

    for ((i = 0; i <= len - 1; i++)); do
        for ((j = 0; j <= len - 2; j++)); do
            if (( arr[j] > arr[(( j + 1 ))] )); then
                (( tmp = arr[(( j + 1 ))] ))
                (( arr[(( j + 1 ))] = arr[j] ))
                (( arr[j] = tmp ))
            fi
        done
    done
    echo ${arr[*]}
}

... And that's it for the simplest bubble sort method. Now, as you might imagine, computer scientists have optimized this to the fiery lakes of Michigan and back, so we'll come back to this in the future and talk about how to optimize it. For now, it's fine to just bask in the simplicity that is bubble sort. Trust me, there are plenty of more complicated algorithms that do precisely the same thing, only much, much better (for most cases).

Example Code

function bubble_sort!(a::Vector{Float64})
    n = length(a)
    for i = 1:n
        for j = 1:n-1
            if(a[j] < a[j+1])
                a[j], a[j+1] = a[j+1], a[j]
            end
        end
    end
end


function main()
    a = [1., 3, 2, 4, 5, 10, 50, 7, 1.5, 0.3]
    bubble_sort!(a)
    println(a)
end

main()
BubbleSort.cs
// submitted by Julian Schacher (jspp)
using System;
using System.Collections.Generic;

namespace BubbleSort
{
    public static class BubbleSort
    {
        public static List<T> RunBubbleSort<T>(List<T> list) where T : IComparable<T>
        {
            var length = list.Count;

            for (int i = 0; i < length; i++)
            {
                for (int j = 1; j < length; j++)
                {
                    if (list[j - 1].CompareTo(list[j]) > 0)
                    {
                        var temp = list[j - 1];
                        list[j - 1] = list[j];
                        list[j] = temp;
                    }
                }
            }

            return list;
        }
    }
}
Program.cs
// submitted by Julian Schacher (jspp)
using System;
using System.Collections.Generic;

namespace BubbleSort
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("BubbleSort");
            var listBubble = new List<int>() { 1, 2, 6, 4, 9, 54, 3, 2, 7, 15 };
            Console.Write("unsorted: ");
            foreach (var number in listBubble)
                Console.Write(number + " ");
            Console.WriteLine();
            listBubble = BubbleSort.RunBubbleSort(listBubble);
            Console.Write("sorted: ");
            foreach (var number in listBubble)
                Console.Write(number + " ");
            Console.WriteLine();
        }
    }
}
#include <stdio.h>

void print_range(int *array, size_t n) {
    for (size_t i = 0; i < n; ++i) {
        printf("%d ", array[i]);
    }
    printf("\n");
}

void bubble_sort(int *array, size_t n) {
    for (size_t i = 0; i < n; ++i) {
        for (size_t j = 0; j < n - 1; ++j) {
            if (array[j] > array[j + 1]) {
                int tmp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = tmp;
            }
        }
    }
}

int main() {
    int array[] = {1, 45, 756, 4569, 56, 3, 8, 5, -10, -4};
    size_t N = sizeof(array) / sizeof(*array);

    printf("Unsorted array:\n");
    print_range(array, N);

    bubble_sort(array, N);

    printf("\nSorted array:\n");
    print_range(array, N);

    return 0;
}
public class Bubble {
    static void bubbleSort(int[] arr) {
        for (int r = arr.length - 1; r > 0; r--) {
            for (int i = 0; i < r; i++) {
                if(arr[i] > arr[i + 1]) {
                    int tmp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = tmp;
                }
            }
        }
    }


    public static void main(String[] args) {
        int[] test = new int[]{20, -3, 50, 1, -6, 59};

        System.out.println("Unsorted array :");
        for (int i = 0; i < test.length; i++) {
            System.out.print(test[i] + " ");
        }

        bubbleSort(test);

        System.out.println("\n\nSorted array :");
        for (int i = 0; i < test.length; i++) {
            System.out.print(test[i] + " ");
        }
        System.out.println("");
    }
}
fun bubbleSort(input: MutableList<Int>) {
    for (i in (input.size - 1) downTo 0) {
        for (j in 0 until i) {
            if (input[j] > input[j + 1]) {
                input[j] = input[j + 1].also {
                    input[j + 1] = input[j]
                }
            }
        }
    }
}

fun main(args: Array<String>) {
    var list = mutableListOf(4, 2, 9, 20, 11, 30, 1, 0);
    println("Original $list")
    bubbleSort(list)
    println("Sorted   $list")
}
function bubbleSort(arr) {
  let tmp;
  for (let i = 0; i < arr.length; i++) {
    for (let k = 0; k < arr.length - 1; k++) {
      if (arr[k] > arr[k + 1]) {
        tmp = arr[k];
        arr[k] = arr[k + 1];
        arr[k + 1] = tmp;
      }
    }
  }
}

function main() {
  const testArray = [1, 3, 2, 4, 5, 10, 50, 7, 1.5, 0.3];
  bubbleSort(testArray);
  console.log(testArray);
}

main();
import random


def bubble_sort(array):
    len_array = len(array)
    for i in range(len_array):
        for j in range(len_array - i - 1):
            if(array[j] > array[j+1]):
                array[j], array[j+1] = array[j+1], array[j] #swap elements in the list

def main():
    number = [random.randint(0, 1000) for _ in range(10)]
    print("Before Sorting  {}".format(number))
    bubble_sort(number)
    print("After Sorting  {}".format(number))

main()
function sorted_array = bubblesort(array)
    for i = 1 : length(array)
        for j = 1 : length(array) - i
            if array(j) > array(j+1)
                % swap elements in the list
                temp       = array(j);
                array(j)   = array(j+1);
                array(j+1) = temp;
            end
        end
    end
    sorted_array = array;
end

function main()
    array = floor(rand(1, 7) * 100);
    disp('Before Sorting:')
    disp(array)

    array = bubble_sort(array);
    disp('After Sorting:')
    disp(array)
end

main()
function bubble_sort(arr)
  for i = 1,#arr-1 do
    for j = 1,#arr-1 do
      if arr[j] > arr[j+1] then
        arr[j], arr[j+1] = arr[j+1], arr[j]
      end
    end
  end
end

local arr = {1, 45, 756, 4569, 56, 3, 8, 5, -10, -4}
print(("Unsorted array: {%s}"):format(table.concat(arr,", ")))

bubble_sort(arr)

print(("Sorted array: {%s}"):format(table.concat(arr,", ")))
bubbleSort :: (Ord a) => [a] -> [a]
bubbleSort x = (!!length x) $ iterate bubble x
  where bubble (x:y:r)
          | x <= y    = x : bubble (y:r)
          | otherwise = y : bubble (x:r)
        bubble x = x
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <iterator>

template <class Iter>
void print_range(Iter first, Iter last) {
  for (auto it = first; it != last; ++it)
    std::cout << *it << " ";
  std::cout << std::endl;
}

template <class Iter>
void bubble_sort(Iter first, Iter last) {
  for (auto it1 = first; it1 != last; ++it1) {
    for (auto it2 = first; it2 + 1 != last; ++it2) {
      // these are unsorted! gotta swap 'em
      if (*(it2 + 1) < *it2) {
        std::iter_swap(it2, it2 + 1);
      }
    }
  }
}

int main() {
  int input[] = {1, 45, 756, 4569, 56, 3, 8, 5, -10, -4};

  std::cout << "Unsorted array:\n";
  print_range(std::begin(input), std::end(input));

  bubble_sort(std::begin(input), std::end(input));

  std::cout << "\nSorted array:\n";
  print_range(std::begin(input), std::end(input));
}
extern crate rand; // External crate that provides random number generation tools

use rand::{thread_rng, Rng}; // Used for random number generation
use rand::distributions::Uniform; // Used for a uniform distribution

fn bubble_sort(a: &mut [u32]) {
    let n = a.len();

    for _ in 0..n {
        for j in 1..n {
            if a[j - 1] > a[j] {
                a.swap(j, j - 1);
            }
        }
    }
}

fn main() {
    let mut rng = thread_rng(); // Create random number generator
    let num_range = Uniform::new_inclusive(0, 10000); // Obtain uniform distribution of range [0, 10000]
    let mut rand_vec: Vec<u32> = rng.sample_iter(&num_range).take(10).collect();
    // Generates random values over that range, take 10 values from it and collect in vector

    println!("Before sorting: {:?}", rand_vec);
    bubble_sort(&mut rand_vec);
    println!("After sorting: {:?}", rand_vec);
}
import std.range : hasAssignableElements, isRandomAccessRange, hasLength;

void bubbleSort(R)(ref R range)
if (isRandomAccessRange!R && hasAssignableElements!R && hasLength!R)
{
    import std.algorithm : swap;

    foreach (i; 0 .. range.length) {
        bool isSorted = true;
        foreach (j; 0 .. range.length - 1)
            if (range[j + 1] < range[j]) {
                swap(range[j + 1], range[j]);
                isSorted = false;
            }
        if (isSorted)
            return;
    }
}

void main() @safe
{
    import std.stdio : writefln;
    import std.range : generate, take;
    import std.array : array;
    import std.random : uniform01;

    auto input = generate!(() => uniform01!float).take(10).array;
    writefln!"before sorting:\n%s"(input);
    bubbleSort(input);
    writefln!"after sorting:\n%s"(input);
}
// Submitted by Chinmaya Mahesh (chin123)

package main

import "fmt"

func bubbleSort(array []int) {
    n := len(array)
    for i := 0; i < n-1; i++ {
        swapped := false
        for j := 0; j < n-i-1; j++ {
            if array[j] > array[j+1] {
                array[j], array[j+1] = array[j+1], array[j]
                swapped = true
            }
        }
        if !swapped {
            break
        }
    }
}

func main() {
    array := [10]int{1, 45, 756, 4569, 56, 3, 8, 5, -10, -4}
    fmt.Println("Unsorted array:", array)

    bubbleSort(array[:])

    fmt.Println("Sorted array:", array)
}
#lang racket

(provide bubbleSort)


(define bubbleSort
  (case-lambda [(l) (bubbleSort l (length l))]
               [(l n) (if (= n 1)
                          l
                          (bubbleSort (pass l 0 n) (- n 1)))]))

; a single pass, if this is the nth pass, then we know that the (n - 1) last elements are already sorted
(define (pass l counter n)
  (let ([x (first l)]
        [y (second l)]
        [r (drop l 2)])
    (cond [(= (- n counter) 2) (cons (min x y) (cons (max x y) r))]
          [(cons (min x y) (pass  (cons (max x y) r) (+ counter 1) n))])))


((lambda (x) (display (bubbleSort x))) (read))
func bubbleSort(sortArray: inout [Int]) -> [Int] {
    for i in (1..<sortArray.count).reversed() {
        for j in 0..<i {
            if sortArray[j] > sortArray[j+1] {
                let temp = sortArray[j]
                sortArray[j] = sortArray[j + 1]
                sortArray[j + 1] = temp
            }
        }
    }

    return sortArray
}

func main() {
    var testArray = [4,5,123,759,-132,8940,24,34,-5]
    print(bubbleSort(sortArray: &testArray))
}

main()
:"SUBMITTED BY GIBUS WEARING BRONY"
:"L IS LENGTH OF LIST"
:dim(L1)→L
:For(A,1,L)
:For(X,1,L-1)
:If L1(X)>L1(X+1)
:Then
:L1(X)→Y
:L1(X+1)→L1(X)
:Y→L1(X+1)
:End
:End
:End
:Disp L1
#!/usr/bin/env ruby

def bubble_sort(arr)
    (0..arr.length - 1).each do
        (0..arr.length - 2).each do |k|
            if arr[k] > arr[k + 1]
                arr[k + 1], arr[k] = arr[k], arr[k + 1]
            end
        end
    end

    return arr
end

def main
    range = [200, 79, 69, 45, 32, 5, 15, 88, 620, 125]    
    puts "The range before sorting is #{range}"
    range = bubble_sort(range)
    puts "The range after sorting is #{range}"
end

main()
def bubble_sort(arr)
  arr = arr.dup 
  (0 ... arr.size).each do 
    (0 ... arr.size-1).each do |k| 
      if arr[k] > arr[k+1]
        arr[k+1],arr[k] = arr[k],arr[k+1]
      end
    end
  end 
  arr
end

def main 
  number = 10.times.map{rand(0..1_000)}.to_a 
  pp "The array before sorting is #{number}"
  number = bubble_sort number 
  pp "The array after  sorting is #{number}"
end 

main
<?php
declare(strict_types=1);

function bubble_sort(array $arr): array
{
    for ($i = 0, $length = count($arr); $i < $length; $i++) {
        for ($j = 1; $j < $length; $j++) {
            if ($arr[$j - 1] > $arr[$j]) {
                $tmp = $arr[$j - 1];
                $arr[$j - 1] = $arr[$j];
                $arr[$j] = $tmp;
            }
        }
    }

    return $arr;
}

$unsorted = [1, 2, 6, 47, 4, 9, 3, 7, 8, 23, 15];
$bubble_sorted = bubble_sort($unsorted);

printf('Unsorted: %s', implode(',', $unsorted));
echo PHP_EOL;
printf('Sorted: %s', implode(',', $bubble_sorted));
echo PHP_EOL;
;;;; Bubble sort implementation

(defun bubble-up (list)
  (if
    (< (length list) 2) 
    list  
    (if 
      (> (first list) (second list))
      (cons 
        (second list) 
        (bubble-up 
          (cons 
            (first list) 
            (rest (rest list)))))           
      (cons 
        (first list)
        (bubble-up
          (rest list))))))

(defun bubble-sort (list)
  (if 
    (< (length list) 2)
    list
    (let* ((new-list (bubble-up list)))
      (append 
        (bubble-sort (butlast new-list)) 
        (last new-list)))))

;; The built-in sort: (sort (list 5 4 3 2 1) #'<)
(print 
  (bubble-sort (list 5 4 3 2 1)))
(print
  (bubble-sort (list 1 2 3 3 2 1)))
proc print_array(a: openArray[int]) =
  for n in 0 .. < len(a):
    echo a[n]

proc bubble_sort(a: var openArray[int]) =
  for i in 0 .. < len(a) - 1:
    for j in 0 .. < len(a) - 1:
      if a[j + 1] < a[j]:
        swap(a[j], a[j + 1])

var x: array[10,int] =  [32, 32, 64, 16, 128, 8, 256, 4, 512, 2]
echo "Unsorted:"
print_array(x)
echo "\nSorted:"
bubble_sort(x)
print_array(x)
.intel_syntax noprefix

.section .rodata
  array:
    .align  16
    .int    1, 45, 756, 4569, 56, 3, 8, 5, -10, -4
    .equ    array_len, (.-array) / 4
  array_fmt: .string "%d "
  lf:        .string "\n"
  unsorted:  .string "Unsorted array: "
  sorted:    .string "Sorted array: "

.section .text
  .global main
  .extern printf

print_array:
  push   r12
  push   r13

  mov    r12, rdi                 # Loop variable
  lea    r13, [rdi + 4*rsi]       # Pointer after the last element

print_array_loop:
  cmp    r12, r13                 # If we're done iterating over the array then bail
  jge    print_array_done
  mov    rdi, OFFSET array_fmt    # Otherwise print the current value
  mov    esi, DWORD PTR [r12]
  xor    rax, rax
  call   printf
  lea    r12, [r12 + 4]           # And increment the loop variable pointer
  jmp    print_array_loop

print_array_done:
  mov    rdi, OFFSET lf           # Print a closing newline
  xor    rax, rax
  call   printf

  pop    r13
  pop    r12
  ret

bubble_sort:
  xor    rcx, rcx                 # The outer loop counter
  lea    rdx, [rdi + 4*rsi - 4]   # The end address for the inner loop

outer_loop:
  cmp    rcx, rsi                 # We first check if the outer loop is done
  jge    bubble_sort_done         # And if it is, return
  mov    rax, rdi                 # Otherwise we initialize the loop variable of the inner loop
inner_loop:
  mov    r8d, DWORD PTR [rax]     # Load array[j] and array[j+1] through a pointer
  mov    r9d, DWORD PTR [rax + 4]
  cmp    r8d, r9d                 # If array[j] <= array[j+1]
  jle    loop_counters            # Then we can skip this iteration
  mov    DWORD PTR [rax], r9d     # Otherwise swap the values
  mov    DWORD PTR [rax + 4], r8d
loop_counters:
  lea    rax, [rax + 4]           # First, advance the inner loop
  cmp    rax, rdx
  jl     inner_loop               # And in case it's not done, repeat
  inc    rcx                      # If it is done, go back to doing the outer loop
  jmp    outer_loop

bubble_sort_done:
  ret

main:
  # Set up our stack
  sub    rsp, 40

  # We load the array in chunks onto the stack
  movaps xmm0, XMMWORD PTR [array]
  movaps XMMWORD PTR [rsp], xmm0
  movaps xmm0, XMMWORD PTR [array + 16]
  movaps XMMWORD PTR [rsp + 16], xmm0
  mov    rax, QWORD PTR [array + 32]
  mov    QWORD PTR [rsp + 32], rax

  # Print the unsorted array
  mov    rdi, OFFSET unsorted
  xor    rax, rax
  call   printf

  mov    rdi, rsp
  mov    rsi, array_len
  call   print_array

  # Sort
  mov    rdi, rsp
  mov    rsi, array_len
  call   bubble_sort

  # Print the sorted array
  mov    rdi, OFFSET sorted
  xor    rax, rax
  call   printf

  mov    rdi, rsp
  mov    rsi, array_len
  call   print_array

  # Restore the stack pointer, set return value to 0
  add    rsp, 40
  xor    rax, rax
  ret
PROGRAM main

    IMPLICIT NONE
    REAL(8), DIMENSION(10) :: A

    A = (/ 1d0, 3d0, 2d0, 4d0, 5d0, 10d0, 50d0, 7d0, 1.5d0, 0.3d0 /)

    WRITE(*,*) 'Input vector'
    WRITE(*,'( F6.2 )') A
    WRITE(*,*) ' '

    CALL bubblesort(A)

    WRITE(*,*) 'Output vector'
    WRITE(*,'(F6.2)') A

CONTAINS

SUBROUTINE bubblesort(array)

    IMPLICIT NONE
    INTEGER                              :: array_length, i, j, n
    REAL(8)                              :: tmp
    REAL(8), DIMENSION(:), INTENT(INOUT) :: array

    array_length = size(array)
    n = array_length

    DO i=1, n
        DO j=1, n-1
            IF ( array(j) > array(j+1) ) THEN

                tmp        = array(j+1)
                array(j+1) = array(j)
                array(j)   = tmp

            END IF
        END DO
    END DO
END SUBROUTINE bubblesort

END PROGRAM main
make some extra space for a marker
>>>

build array
>>++++
>>++++++
>>+++++
>>+++
>>+++++++
>>+
>>+++
>>++ 

move to starting point
>>>

set loop marker to 1 and starts loop
+
[

delete loop marker
-<<<<<

if there is a number here
[

add it to the empty space to the right 
and subtract it from the next number
[->+>-<<]

undo subtraction once without a zero check in case the numbers are equal
+>>+<-

then as long as the left number is bigger than zero
[<+>>

if the number to the right becomes a zero in the process 
due to buffer overflow set a swap marker
[<<<]<<[<<<<<+>>]

otherwise continue resetting numbers
>>>>>+<-]

set a "correct" marker between numbers
+

check swap marker
<<<<<<

if swap marker is set delete "correct" marker
[->>>>>>->

and swap the numbers
[-<+>]<<[->>+<<]>[-<+>]

go to next pair
<<<<<<]>>>

repeat until end of array
]

go to leftmost "correct" marker
>>>

delete marker and jump to the next one if it's 1
[->>]

else delete all markers and set repetition marker
>[>[-]>>+<]>]

program stops three places to the right of the 
sorted array
"Add this method to the SequenceableCollection class in the browser:"
SequenceableCollection>>bubbleSort
    "Bubble sort for a collection."
    | len swapper thisElem nextElem |
    len  := self size.
    1 to: len - 1 do:  [ :iteration |
        1 to: len - 1 do: [ :index |
            thisElem := self at: index.
            nextElem := self at: index + 1.
            (thisElem > nextElem) ifTrue: [ 
                self at: thisIndex + 1 put: thisElem.
                self at: thisIndex put: nextElem.
            ]
        ]
    ]

"Then run this anywhere in your code: "
#(4 3 2 1 6 5) bubbleSort "outputs:  #(1 2 3 4 5 6)"
object BubbleSort {

  def bubbleDown(list: List[Int]): List[Int] =
    list match {
      case a :: b :: tail if a < b => b :: bubbleDown(a :: tail)
      case a :: b :: tail => a :: bubbleDown(b :: tail)
      case _ => list
    }

  def bubbleSort(list: List[Int]): List[Int] =
    bubbleDown(list) match {
      case unsorted :+ smallest => smallest :: bubbleDown(unsorted)
      case _ => list
    }

  def main(args: Array[String]): Unit = {
    val unsorted = List(9, 2, 0, 5, 3, 8, 1, 9, 4, 0, 7, 0, 9, 9, 0)

    println("Unsorted list is " + unsorted)
    println("  Sorted list is " + bubbleSort(unsorted))
  }
}
🐇 🥇 🍇
  🐇 ❗️ 🛁 numbers 🍨🐚💯🍆 🍇
    🐔 numbers❗️ ➡️ count

    🔂 i 🆕⏩⏩ 0 count❗️ 🍇
      🔂 j 🆕⏩⏩ 1 count❗️ 🍇
        ↪️ 🐽 numbers j ➖  1❗️ ▶️ 🐽 numbers j❗️ 🍇
          🐽 numbers j ➖ 1❗️ ➡️ temp
          🐷 numbers j ➖ 1 🐽 numbers j❗️❗️
          🐷 numbers j temp❗️
        🍉
      🍉
    🍉
  🍉
🍉

🏁 🍇
  🍨 1.7 -3.0 2.5 2.0 -6.0 4.4 50.0 7.0 1.5 -4.3 0.3 🍆  ➡️ numbers

  😀 🔤unordered:🔤❗️
  🔂 number numbers 🍇
    😀 🔡 number 10❗️❗️
  🍉

  🛁🐇🥇 numbers❗️

  😀 🔤ordered:🔤❗️
  🔂 number numbers 🍇
    😀 🔡 number 10❗️❗️
  🍉
🍉
#!/usr/bin/env bash
bubble_sort() {
    local i
    local j
    local tmp
    local len
    local arr
    arr=("[email protected]")
    (( len = ${#arr[@]} ))

    for ((i = 0; i <= len - 1; i++)); do
        for ((j = 0; j <= len - 2; j++)); do
            if (( arr[j] > arr[(( j + 1 ))] )); then
                (( tmp = arr[(( j + 1 ))] ))
                (( arr[(( j + 1 ))] = arr[j] ))
                (( arr[j] = tmp ))
            fi
        done
    done
    echo ${arr[*]}
}

arr=(1 45 756 4569 56 3 8 5 -10 -4)
echo "Unsorted array: ${arr[*]}"
tmp=$(bubble_sort "${arr[@]}")
echo "Sorted array: ${tmp[*]}"

results matching ""

    No results matching ""