Difference between revisions of "Bubble sort"

From CodeCodex

(Go)
 
(41 intermediate revisions by 30 users not shown)
Line 1: Line 1:
 +
Bubble sort examples in 33 programming languages.
 
{{Template:Infobox See Also Sort}}
 
{{Template:Infobox See Also Sort}}
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
 +
 
==Implementation==
 
==Implementation==
 
===Pseudocode===
 
===Pseudocode===
'''function''' bubblesort (A : ''list''[1..n]) {
+
prozedur bubbleSort( A : Liste sortierbarer Elemente )
    '''var''' ''int'' i, j;
+
  n := Länge( A )
    '''for''' i '''from''' n '''downto''' 1 {
+
  wiederhole
        '''for''' j '''from''' 1 '''to''' i-1 {
+
    vertauscht := falsch
            '''if''' (A[j] > A[j+1])
+
    für jedes i von 1 bis n - 1 wiederhole
                swap(A[j], A[j+1])
+
      falls A[ i ] > A[ i + 1 ] dann
        }
+
        vertausche( A[ i ], A[ i + 1 ] )
    }
+
        vertauscht := wahr
}
+
      ende falls
 +
    ende für
 +
    n := n - 1
 +
  solange vertauscht und n > 1
 +
prozedur ende
  
===Ada===
+
No complaints on this end, simlpy a good piece.
Ada implementation, using user-defined type ''Data_T'' holding the values, each having type ''Item_T''.
+
  
  procedure Bubble_Sort (Data : in out Data_T) is
 
      procedure Swap(A : in out Item_T; B : in out Item_T) is
 
        T : constant Item_T := A;
 
      begin
 
        A := B;
 
        B := T;
 
      end Swap;
 
      Finished : Boolean;
 
      Top      : Integer := Data'Last;
 
  begin
 
      loop
 
        Finished := True;
 
        Top := Top - 1;
 
        for I in Data'First..Top loop
 
            if Data(I) > Data(I + 1) then
 
              Swap (Data(I), Data(I + 1));
 
              Finished := False;
 
            end if;
 
        end loop;
 
        exit when Finished;
 
      end loop;
 
  end Bubble_Sort;
 
  
===Assembly===
+
'''Source(s):'''  [http://downloadranking.com/support.php Bubble sort]
MASM. Sorts an array of DWORDS with ''len'' elements.
+
 
<pre>
+
  bs proc array:DWORD,len:DWORD
+
mov ecx,len
+
mov edx,array
+
bs_o:
+
xor ebp,ebp
+
bs_i:
+
mov eax,DWORD PTR [edx+ebp*4+4]
+
cmp DWORD PTR [edx+ebp*4],eax
+
jb @F
+
xchg eax,DWORD PTR [edx+ebp*4]
+
mov DWORD PTR [edx+ebp*4+4],eax
+
@@:
+
add ebp,1
+
cmp ebp,ecx
+
jb bs_i
+
loop bs_o
+
pop ebp
+
retn 8
+
  bs endp
+
</pre>
+
  
 
===AutoIt===
 
===AutoIt===
Line 78: Line 44:
 
EndFunc  ;==>BubbleSort
 
EndFunc  ;==>BubbleSort
 
</pre>
 
</pre>
 +
 +
<pre>
 +
=====================================================================
 +
  Func BubbleSort(ByRef $bs_array)
 +
For $i = UBound($bs_array) - 1 To 1 Step - 1
 +
For $j = 0 To $i
 +
If $bs_array[$j - 1] > $bs_array[$j] Then
 +
  Swap($bs_array[$j - 1],$bs_array[$j])
 +
EndIf
 +
Next
 +
Next
 +
Return $bs_array
 +
EndFunc  ;==>BubbleSort
 +
 +
Func Swap(Byref $x, Byref $y)
 +
  $temp = $x
 +
  $x = $y
 +
  $y = $temp
 +
EndFunc
 +
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
===Blitz BASIC===
 
===Blitz BASIC===
Line 102: Line 92:
 
  End Function
 
  End Function
  
===C===
 
1:
 
'''void''' bubbleSort('''int''' *array, '''int''' length)
 
{
 
  '''int''' i, j, temp;
 
  '''int''' test; /*use this only if unsure whether the list is already sorted or not*/
 
  '''for'''(i = length - 1; i > 0; i--)
 
  {
 
    test=0;
 
    '''for'''(j = 0; j < i; j++)
 
    {
 
      '''if'''(array[j] > array[j+1]) /* compare neighboring elements */
 
      {
 
        temp = array[j];    /* swap array[j] and array[j+1] */
 
        array[j] = array[j+1];
 
        array[j+1] = temp;
 
        test=1;
 
      }
 
    } /*end for j*/
 
    '''if'''(test==0) '''break'''; /*will exit if the list is sorted!*/
 
  } /*end for i*/
 
     
 
}/*end bubbleSort*/
 
  
2:
+
'''Source(s):''' [http://downloadranking.com/support.php  Bubble sort]
  '''void''' bubbleSort_flag('''int''' a[], '''int''' n)
+
  {
+
    '''int''' i, j, temp, flag;
+
    '''for'''(i=n-1; i>0; i--)
+
    {
+
      flag = 1;
+
      '''for'''(j=0; i>j; j++)
+
      {
+
        '''if'''(a[j]>a[j+1])
+
        {
+
          flag = 0;
+
          temp = a[j];
+
          a[j] = a[j+1];
+
          a[j+1] = temp;
+
        }
+
      }
+
      //out this block when flag is true
+
      //i.e. inner loop performed no swaps, so the list is already sorted
+
      '''if'''(flag)
+
        '''break''';
+
    }
+
  }
+
  
3:
 
  '''void'''    sort_len('''int''' *tab, '''int''' len)
 
  {
 
    '''int'''  tmp;
 
    '''int'''  again;
 
    '''int'''  i;
 
 
 
    '''for''' (again = 1; again;)
 
      '''for''' (again = 0, i = 0; i < (len - 1); i++)
 
        {
 
          '''if''' (tab[i] > tab[i + 1])
 
            {
 
              tmp = tab[i];
 
              tab[i] = tab[i + 1];
 
              tab[i + 1] = tmp;
 
              again = 1;
 
            }
 
        }
 
  }
 
  
 
===C++===
 
===C++===
Line 195: Line 121:
 
  }
 
  }
 
</pre>
 
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
===C#===
 
===C#===
Line 216: Line 146:
 
  }
 
  }
 
</pre>
 
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
===C# 2.0===
 
===C# 2.0===
Line 236: Line 170:
 
  }
 
  }
 
</pre>
 
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
 +
 +
===Clojure===
 +
<pre class="clojure">
 +
(defn bubble-sort [m]
 +
  (for [i (reverse (range (count m)))]
 +
    (dotimes [j i]
 +
      (when (< (aget m i) (aget m j))
 +
        (let [tmp (aget m i)]
 +
          (aset m i (aget m j))
 +
          (aset m j tmp))))))
 +
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
===COBOL===
 
===COBOL===
Line 298: Line 251:
 
       MY-SORT-EXIT.
 
       MY-SORT-EXIT.
 
           EXIT.
 
           EXIT.
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
===D===
 
===D===
Line 315: Line 272:
 
     }
 
     }
 
  }
 
  }
 +
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
 +
 +
===Erlang===
 +
<pre>
 +
bubble_sort([]) -> [];
 +
bubble_sort(List) when is_list(List) ->
 +
    bubble_sort(List, []).
 +
 +
bubble_sort([X], Sorted) -> [X | Sorted];
 +
bubble_sort(List, Sorted) ->
 +
    [Max | Rest] = bubble_move(List, []),
 +
    bubble_sort(Rest, [Max | Sorted]).
 +
 +
bubble_move([X], Rest) -> [X | Rest];
 +
bubble_move([X, Y | T], Rest) ->
 +
    if X > Y -> bubble_move([X | T], [Y | Rest]);
 +
        true -> bubble_move([Y | T], [X | Rest])
 +
    end.
 
</pre>
 
</pre>
  
Line 331: Line 310:
 
   go ls (Seq.length ls)
 
   go ls (Seq.length ls)
 
</pre>
 
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
===Fortran===
 
===Fortran===
Line 374: Line 357:
 
       END SUBROUTINE sort
 
       END SUBROUTINE sort
 
</pre>
 
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
 +
 +
===GML===
 +
<pre>
 +
//Arg0 = number of items; Arg1+ = items;
 +
 +
//Variable declarations
 +
var inum,swapped;
 +
items=0;
 +
inum=argument0;
 +
swapped=0;
 +
 +
//To collect the items into an array
 +
for (i=0;i<inum;i+=1) {
 +
    items[i]=argument[i+1];
 +
}
 +
 +
//Main bubble sort loop
 +
while (swapped < inum-1) {
 +
    for (i=0;i<inum-1;i+=1) {
 +
        if items[i] > items[i + 1] {
 +
            var k;
 +
            k=items[i];
 +
            items[i]=items[i+1];
 +
            items[i+1]=k;
 +
        }
 +
        else {swapped+=1;}
 +
    }
 +
}
 +
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
===Go===
 
===Go===
 
<pre>
 
<pre>
 +
func BubbleSort(nums []int) {
 +
    unsorted := true
 +
    for unsorted {
 +
        unsorted = false
 +
        for i := len(nums) - 1; i > 0; i-- {
 +
            if nums[i] < nums[i-1] {
 +
                nums[i], nums[i-1] = nums[i-1], nums[i]
 +
                unsorted = true
 +
            } 
 +
        } 
 +
    } 
 +
}
 +
 +
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
===Haskell===
 
===Haskell===
 
  bubbleSort :: [Int] -> [Int]
 
  bubbleSort :: [Int] -> [Int]
 
  bubbleSort [] = []
 
  bubbleSort [] = []
  bubbleSort xs =
+
  bubbleSort (x:xs) = step $ '''foldl''' go (x,[]) xs '''where'''
    '''iterate''' swapPass xs !! ('''length''' xs - 1)
+
  go (y,acc) x = ('''min''' x y, '''max''' x y : acc)
    '''where'''
+
  step (x,acc) = x : bubbleSort acc
      swapPass [x] = [x]
+
 
      swapPass (x:y:zs)
+
 
          | x > y    = y : swapPass (x:zs)
+
'''Source(s):''' [http://downloadranking.com/support.php  Bubble sort]
          | '''otherwise''' = x : swapPass (y:zs)
+
 
  
 
===Java===
 
===Java===
Line 446: Line 484:
 
  }
 
  }
 
</pre>
 
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
  
  
Line 457: Line 498:
 
Array.prototype.bubble_sort = function() {
 
Array.prototype.bubble_sort = function() {
 
     var i, j;
 
     var i, j;
 +
    var swapped;
 
     var newarray = this.slice(0);
 
     var newarray = this.slice(0);
 
     var swap = function(j, k) {
 
     var swap = function(j, k) {
Line 464: Line 506:
 
       return(true);
 
       return(true);
 
     }
 
     }
    var swapped = false;
 
 
     for(i=1; i<newarray.length; i++) {
 
     for(i=1; i<newarray.length; i++) {
 +
      swapped = false;
 
       for(j=0; j<newarray.length - i; j++) {
 
       for(j=0; j<newarray.length - i; j++) {
 
         if (newarray[j+1] < newarray[j]) {
 
         if (newarray[j+1] < newarray[j]) {
Line 494: Line 536:
 
</html>  
 
</html>  
 
</pre>
 
</pre>
 +
I just dont get this
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
===Maya Embedded Language===
 
===Maya Embedded Language===
Line 525: Line 572:
 
  return $list;
 
  return $list;
 
  }
 
  }
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
  
  
Line 558: Line 608:
 
  }
 
  }
 
</pre>
 
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
===OCaml===
 
===OCaml===
Line 576: Line 630:
 
- : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9]
 
- : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9]
 
</pre>
 
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
===Pascal===
 
===Pascal===
Line 699: Line 757:
 
   End;
 
   End;
 
  End;
 
  End;
</source>
+
</pre>
  
 
A simplified version:
 
A simplified version:
  
<source lang="pascal">
+
<pre class="pascal">
 
+
 
  Procedure BubbleSort(var a:IntArray; size:integer);
 
  Procedure BubbleSort(var a:IntArray; size:integer);
 
   var i,j,temp: integer;
 
   var i,j,temp: integer;
Line 716: Line 773:
 
   end;
 
   end;
 
</pre>
 
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
  
  
Line 760: Line 820:
 
  print bubble_sort qw(6 5 3 8 7 4);
 
  print bubble_sort qw(6 5 3 8 7 4);
 
</pre>
 
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
===PHP===
 
===PHP===
Line 780: Line 844:
  
 
</pre>
 
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
===Progress ABL/4GL===
 
===Progress ABL/4GL===
Line 808: Line 876:
 
END FUNCTION.
 
END FUNCTION.
 
</pre>
 
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
===Python===
 
===Python===
  
 +
<pre class="python">
 
  def BubbleSort(lst):
 
  def BubbleSort(lst):
 
     lst = list(lst) #copy collection to list  
 
     lst = list(lst) #copy collection to list  
Line 818: Line 891:
 
                 lst[i], lst[i + 1] = lst[i + 1], lst[i]
 
                 lst[i], lst[i + 1] = lst[i + 1], lst[i]
 
     return lst
 
     return lst
 
+
</pre>
-- another method --
+
Another method
 +
<pre class="python">
 
  def BubbleSort2(lst):
 
  def BubbleSort2(lst):
 
     lst = list(lst)
 
     lst = list(lst)
Line 826: Line 900:
 
         swapped = False
 
         swapped = False
 
         for i in range(len(lst)-1):
 
         for i in range(len(lst)-1):
             if lst[i] > lst[i+1]:
+
             if lst[i] < lst[i+1]:
 
                 lst[i], lst[i+1] = lst[i+1], lst[i]
 
                 lst[i], lst[i+1] = lst[i+1], lst[i]
 
                 swapped = True
 
                 swapped = True
 
     return lst
 
     return lst
 +
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
===QuickBASIC===
 
===QuickBASIC===
Line 875: Line 954:
 
DATA *EOD
 
DATA *EOD
 
</pre>
 
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
===Ruby===
 
===Ruby===
Line 888: Line 971:
 
  end
 
  end
 
</pre>
 
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
===Scheme===
 
===Scheme===
Line 981: Line 1,068:
 
             (swap index (+ index 1))
 
             (swap index (+ index 1))
 
             (float (if (= index 0) 0 (- index 1)))))))
 
             (float (if (= index 0) 0 (- index 1)))))))
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
===Seed7===
 
===Seed7===
Line 1,006: Line 1,097:
  
 
Original source: [http://seed7.sourceforge.net/algorith/sorting.htm#bubbleSort]
 
Original source: [http://seed7.sourceforge.net/algorith/sorting.htm#bubbleSort]
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
===SWI-Prolog===
 
===SWI-Prolog===
Line 1,014: Line 1,109:
 
         bs(R, S)
 
         bs(R, S)
 
     ; S = L.
 
     ; S = L.
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
=== TCL ===
 
=== TCL ===
 +
<pre>
 
   proc bubble_sort {a} {
 
   proc bubble_sort {a} {
 
     if {[llength $a] >= 2} {
 
     if {[llength $a] >= 2} {
Line 1,035: Line 1,135:
 
     return $a
 
     return $a
 
   }
 
   }
 +
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
 +
 +
=== Turbo Prolog ===
 +
<pre>
 +
domains
 +
elem = integer
 +
list = elem*
 +
predicates
 +
swapAll(list, list)
 +
isSorted(list)
 +
bubble(list, list)
 +
clauses
 +
swapAll([H|[]], [H]):-!.
 +
swapAll([H1,H2|T], [H2|R]):-
 +
H1 > H2,
 +
!,
 +
swapAll([H1|T], R).
 +
swapAll([H|T], [H|R]):-
 +
swapAll(T, R).
 +
 +
isSorted([]):-!. %list with no elements is sorted
 +
isSorted([_|[]]):-!. %list with 1 element is sorted
 +
isSorted([H1,H2|L]):-
 +
H1 < H2,
 +
isSorted([H2|L]).
 +
 +
bubble(L, L):-
 +
isSorted(L), !.
 +
bubble(L, R):-
 +
swapAll(L, L2),
 +
bubble(L2, R).
 +
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
=== Turing ===
 
=== Turing ===
Line 1,064: Line 1,204:
 
end for
 
end for
 
</pre>
 
</pre>
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
===VBA===
 
===VBA===
Line 1,098: Line 1,242:
 
</pre>
 
</pre>
  
===GML===
 
<pre>
 
//Arg0 = number of items; Arg1+ = items;
 
  
//Variable declarations
+
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
var inum,swapped;
+
items=0;
+
inum=argument0;
+
swapped=0;
+
  
//To collect the items into an array
 
for (i=0;i<inum;i+=1) {
 
    items[i]=argument[i+1];
 
}
 
 
//Main bubble sort loop
 
while (swapped < inum-1) {
 
    for (i=0;i<inum-1;i+=1) {
 
        if items[i] > items[i + 1] {
 
            var k;
 
            k=items[i];
 
            items[i]=items[i+1];
 
            items[i+1]=k;
 
        }
 
        else {swapped+=1;}
 
    }
 
}
 
</pre>
 
  
 
===Visual Basic===
 
===Visual Basic===
 
<pre class="vb">
 
<pre class="vb">
 
  Sub Bubblesort(Array() as Integer, Length as Integer)
 
  Sub Bubblesort(Array() as Integer, Length as Integer)
    Dim I as Integer
+
    Dim I As Integer
    Dim J as Integer
+
    Dim J As Integer
    Dim Temp as Integer
+
    Dim Temp As Integer
+
    Dim Length As Integer
    For I = Length -1 To 1 Step -1 'the last element on the array does not get sorted.
+
    Dim Array() As String = {}
      For J = 0 to I - 1
+
 
          IF Array(J)>Array(J+1) THEN ' Compare neighboring elements
+
    For I = Length - 1 To 1 Step -1 'the last element on the array does not get sorted.
            Temp = Array(j)  
+
        For J = 0 To I - 1
            Array(J) = Array(J+1)
+
            If Array(J) > Array(J + 1) Then ' Compare neighboring elements
            Array(J+1) = Temp
+
                Temp = Array(J)
          End If
+
                Array(J) = Array(J + 1)
      Next  
+
                Array(J + 1) = Temp
    Next  
+
 
+
            End If
 +
        Next
 +
    Next
 
  End Sub
 
  End Sub
 
</pre>
 
</pre>
Line 1,154: Line 1,275:
 
* [http://www.cs.pitt.edu/~kirk/cs1501/animations/Sort3.html Sorting Applets in C++]
 
* [http://www.cs.pitt.edu/~kirk/cs1501/animations/Sort3.html Sorting Applets in C++]
 
* [http://www.sharpdeveloper.net/content/articles/dot-net-data-structures-and-algorithms.aspx Downloadable .NET Implementation of bubble sort and several other algorithms]
 
* [http://www.sharpdeveloper.net/content/articles/dot-net-data-structures-and-algorithms.aspx Downloadable .NET Implementation of bubble sort and several other algorithms]
 +
 +
 +
'''Source(s):'''  [http://downloadranking.com/support.php  Bubble sort]
 +
  
 
[[Category:Sort algorithms]]
 
[[Category:Sort algorithms]]
Line 1,159: Line 1,284:
 
[[Category:AutoIt]]
 
[[Category:AutoIt]]
 
[[Category:Assembly]]
 
[[Category:Assembly]]
[[Category:BASIC]]
 
 
[[Category:Blitz BASIC]]
 
[[Category:Blitz BASIC]]
 
[[Category:C]]
 
[[Category:C]]
Line 1,166: Line 1,290:
 
[[Category:COBOL]]
 
[[Category:COBOL]]
 
[[Category:D]]
 
[[Category:D]]
 +
[[Category:Erlang]]
 +
[[Category:F sharp]]
 
[[Category:Fortran]]
 
[[Category:Fortran]]
 +
[[Category:GML]]
 
[[Category:Go]]
 
[[Category:Go]]
 
[[Category:Haskell]]
 
[[Category:Haskell]]
Line 1,178: Line 1,305:
 
[[Category:PHP]]
 
[[Category:PHP]]
 
[[Category:Progress ABL/4GL]]
 
[[Category:Progress ABL/4GL]]
 +
[[Category:Prolog]]
 
[[Category:Python]]
 
[[Category:Python]]
 
[[Category:QuickBASIC]]
 
[[Category:QuickBASIC]]
Line 1,183: Line 1,311:
 
[[Category:Scheme]]
 
[[Category:Scheme]]
 
[[Category:Seed7]]
 
[[Category:Seed7]]
 +
[[Category:Tcl]]
 +
[[Category:Turbo Prolog]]
 
[[Category:Turing]]
 
[[Category:Turing]]
 
[[Category:VBA]]
 
[[Category:VBA]]
 
[[Category:Visual Basic]]
 
[[Category:Visual Basic]]

Latest revision as of 05:20, 19 July 2013

Bubble sort examples in 33 programming languages.

Related content:


Source(s): Bubble sort


Implementation[edit]

Pseudocode[edit]

prozedur bubbleSort( A : Liste sortierbarer Elemente )

 n := Länge( A )
 wiederhole
   vertauscht := falsch
   für jedes i von 1 bis n - 1 wiederhole 
     falls A[ i ] > A[ i + 1 ] dann
       vertausche( A[ i ], A[ i + 1 ] )
       vertauscht := wahr
     ende falls
   ende für
   n := n - 1
 solange vertauscht und n > 1

prozedur ende

No complaints on this end, simlpy a good piece.


Source(s): Bubble sort


AutoIt[edit]

Sorts an array of variant data types

Func BubbleSort(ByRef $bs_array)
	For $i = UBound($bs_array) - 1 To 1 Step -1
		For $j = 2 To $i
			If $bs_array[$j - 1] > $bs_array[$j] Then
				$temp = $bs_array[$j - 1]
				$bs_array[$j - 1] = $bs_array[$j]
				$bs_array[$j] = $temp
			EndIf
		Next
	Next
	Return $bs_array
EndFunc   ;==>BubbleSort
=====================================================================
   Func BubbleSort(ByRef $bs_array)
	For $i = UBound($bs_array) - 1 To 1 Step - 1
		For $j = 0 To $i
			If $bs_array[$j - 1] > $bs_array[$j] Then
			   Swap($bs_array[$j - 1],$bs_array[$j])
			EndIf
		Next
	Next
	Return $bs_array
 EndFunc   ;==>BubbleSort
 
Func Swap(Byref $x, Byref $y)
   $temp = $x 
   $x = $y
   $y = $temp
EndFunc


Source(s): Bubble sort


Blitz BASIC[edit]

Function BubbleSortArray( Array[ MaxIndices ] , IndicesUsed = MaxIndices )
   Local Bwd,Fwd
   Local Swapped = True

   For Bwd = IndicesUsed To 1 Step -1
       Swapped = False
       For Fwd = 1 To Bwd-1
           If Array[ Fwd ] > Array[ Fwd+1 ]
               ; Swap indices using XOR
               Array[ Fwd   ] = Array[ Fwd ] Xor Array[ Fwd+1 ]
               Array[ Fwd+1 ] = Array[ Fwd ] Xor Array[ Fwd+1 ]
               Array[ Fwd   ] = Array[ Fwd ] Xor Array[ Fwd+1 ]
               Swapped = True
           Endif
       Next
       If Not Swapped
           Exit
       Endif
   Next
End Function


Source(s): Bubble sort


C++[edit]

C++ can use the C bubble sort above, or use this for random-access iterators of generic containers and a generic comparison operator:

 #include <algorithm>
 
 template<typename Iterator>
 void bubbleSort(Iterator first, Iterator last)
 {
     Iterator i, j;
     for (i = first; i != last; ++i)
         for (j = first; j < i; ++j)
             if (*i < *j)
                 std::iter_swap(i, j);
 }
 
 template<typename Iterator, class StrictWeakOrdering>
 void bubbleSort(Iterator first, Iterator last, StrictWeakOrdering compare)
 {
     Iterator i, j;
     for (i = first; i != last; ++i)
         for (j = first; j < i; ++j)
             if (compare(*i, *j))
                 std::iter_swap(i, j);
 }


Source(s): Bubble sort


C#[edit]

 static void BubbleSort(IComparable[] array)
 {
     int i, j;
     IComparable temp;
     for (i = array.Length - 1; i > 0; i--)
     {
         for (j = 0; j < i; j++)
         {
             if (array[j].CompareTo(array[j + 1]) > 0)
             {
                 temp = array[j];
                 array[j] = array[j + 1];
                 array[j + 1] = temp;
             }
         }
     }
 }


Source(s): Bubble sort


C# 2.0[edit]

 static void BubbleSort<T>(IList<T> list) where T : IComparable<T>
 {
     for (int i = list.Count - 1; i > 0; i--)
     {
         for (int j = 0; j < i; j++)
         {
             IComparable current = list[j];
             IComparable next = list[j + 1];
             if (current.CompareTo(next) > 0)
             {
                 list[j] = next;
                 list[j + 1] = current;
             }
         }
     }
 }


Source(s): Bubble sort


Clojure[edit]

(defn bubble-sort [m]
  (for [i (reverse (range (count m)))]
    (dotimes [j i]
      (when (< (aget m i) (aget m j))
        (let [tmp (aget m i)]
          (aset m i (aget m j))
          (aset m j tmp))))))


Source(s): Bubble sort


COBOL[edit]

If you are dealing with a large volume of data, use the COBOL SORT using sequential files. For sorting a WORKING STORAGE table, the following example assumes that the table is already loaded. The literals "a" indicates the size of the row, and "b" how many rows in the table.

      WORKING-STORAGE SECTION.
     *
      01  WS-SORT-AREA.
          05  WS-SORT-TABLE.
              10  WS-SORT-ROW PIC X(a) OCCURS b.
          05  WS-TEMP-ROW     PIC X(a).
          05  WS-ROW-MAX      PIC S9(4) COMP VALUE b.
          05  WS-SORT-MAX     PIC S9(4) COMP.
          05  WS-SORT-UP      PIC S9(4) COMP.
          05  WS-SORT-DOWN    PIC S9(4) COMP.
          05  WS-SORT-INCR    PIC S9(4) COMP.
          05  WS-SORT-TEST    PIC S9(4) COMP.
     *
       PROCEDURE DIVISION.
     *
       MY-SORT SECTION.
       MY-SORT-START.
     *
     * find the last entry
     *
          PERFORM VARYING WS-SORT-MAX FROM WS-ROW-MAX BY -1
              UNTIL WS-SORT-MAX = ZERO
              OR    WS-SORT-ROW (WS-SORT-MAX) NOT = SPACES
          END-PERFORM.
     *
     * bubble sort into required sequence
     *
          PERFORM VARYING WS-SORT-UP FROM WS-SORT-MAX BY -1
              UNTIL WS-SORT-UP = ZERO
     *
              MOVE ZERO TO WS-SORT-TEST
     *
              PERFORM VARYING WS-SORT-DOWN FROM 1 BY 1
                  UNTIL WS-SORT-DOWN = WS-SORT-UP
     *
                  ADD 1 TO WS-SORT-DOWN GIVING WS-SORT-INCR
     *
                  IF  WS-SORT-ROW (W30-SORT-DOWN)
                    > WS-SORT-ROW (W30-SORT-INCR)
     *
                      MOVE WS-SORT-ROW (WS-SORT-DOWN)
                        TO WS-TEMP-ROW
                      MOVE WS-SORT-ROW (WS-SORT-INCR)
                        TO WS-SORT-ROW (WS-SORT-DOWN)
                      MOVE WS-TEMP-ROW
                        TO WS-SORT-ROW (WS-SORT-INCR)
                      ADD 1 TO WS-SORT-TEST
                  END-IF
              END-PERFORM
     *
              IF  WS-SORT-TEST = ZERO
                  NEXT SENTENCE
              END-IF
          END-PERFORM.
     *
      MY-SORT-EXIT.
          EXIT.


Source(s): Bubble sort


D[edit]

 void bubbleSort(T)(T[] array) {
     bool swapped;
     T temp = void;
     for (int j, i = array.length - 1; i; swapped = false, i--) {
         for (j = 0; j < i; j++)
             if (array[j] > array[j+1]) {
                 temp = array[j];
                 array[j] = array[j+1];
                 array[j+1] = temp;
                 swapped = true;
             }
         if (!swapped) break;
     }
 }


Source(s): Bubble sort


Erlang[edit]

bubble_sort([]) -> [];
bubble_sort(List) when is_list(List) ->
    bubble_sort(List, []).

bubble_sort([X], Sorted) -> [X | Sorted];
bubble_sort(List, Sorted) ->
    [Max | Rest] = bubble_move(List, []),
    bubble_sort(Rest, [Max | Sorted]).

bubble_move([X], Rest) -> [X | Rest];
bubble_move([X, Y | T], Rest) ->
    if X > Y -> bubble_move([X | T], [Y | Rest]);
        true -> bubble_move([Y | T], [X | Rest])
    end.

F#[edit]

let rec bubbleSort ls =
  let rec bs ls =
    match ls with
    | [] -> []
    | x::y::z when x > y -> y::(bs (x::z))
    | x::y -> x::(bs y)
  let rec go ls n =
    match n with
    | 0 -> ls
    | x -> go (bs ls) (x - 1)
  go ls (Seq.length ls)


Source(s): Bubble sort


Fortran[edit]

      SUBROUTINE sort (array_x, array_y, datasize)
 Global Definitions
       REAL array_x(*)
       REAL array_y(*)
       INTEGER datasize
 Local
      REAL x_temp
      REAL y_temp      
      LOGICAL inorder      
      inorder = .false.
      do 90 while (inorder.eq..false.)
       inorder = .true.       
       do 91 i=1, datasize              
 Check Equilivant Points and swap those on Y
       if (array_x(i).eq.array_x(i+1) ) then
        if (array_y(i).lt.array_y(i+1) ) then
         x_temp = array_x(i)
         y_temp = array_y(i)
         array_x(i) = array_x(i+1)
         array_y(i) = array_y(i+1)
         array_x(i+1) = x_temp
         array_y(i+1) = y_temp
         inorder = .false.
        endif
       endif
 If x needs to be swapped, do so 
       if (array_x(i).lt.array_x(i+1) )then
        x_temp = array_x(i)
        y_temp = array_y(i)
        array_x(i) = array_x(i+1)
        array_y(i) = array_y(i+1)
        array_x(i+1) = x_temp
        array_y(i+1) = y_temp
        inorder = .false.
       endif 
91    continue
90    continue       
      END SUBROUTINE sort


Source(s): Bubble sort


GML[edit]

//Arg0 = number of items; Arg1+ = items;

//Variable declarations
var inum,swapped;
items=0;
inum=argument0;
swapped=0;

//To collect the items into an array
for (i=0;i<inum;i+=1) {
    items[i]=argument[i+1];
}

//Main bubble sort loop
while (swapped < inum-1) {
    for (i=0;i<inum-1;i+=1) {
        if items[i] > items[i + 1] {
            var k;
            k=items[i];
            items[i]=items[i+1];
            items[i+1]=k;
        }
        else {swapped+=1;}
    }
}


Source(s): Bubble sort


Go[edit]

func BubbleSort(nums []int) {
    unsorted := true
    for unsorted {
        unsorted = false
        for i := len(nums) - 1; i > 0; i-- {
            if nums[i] < nums[i-1] {
                nums[i], nums[i-1] = nums[i-1], nums[i]
                unsorted = true
            }   
        }   
    }   
}


Source(s): Bubble sort


Haskell[edit]

bubbleSort :: [Int] -> [Int]
bubbleSort [] = []
bubbleSort (x:xs) = step $ foldl go (x,[]) xs where
  go (y,acc) x = (min x y, max x y : acc)
  step (x,acc) = x : bubbleSort acc


Source(s): Bubble sort


Java[edit]

1.

 //Sorts an integer array in ascending order.
 //Parameters:
 //   data - reference to the integer array to sort, must not be null
 //Postcondition:
 //   The array is sorted in ascending order.
 
 public static void bubbleSort(int[] data)
 {
    for (int k = 0; k < data.length - 1; k++)
    {
       boolean isSorted = true;
 
       for (int i = 1; i < data.length - k; i++)
       {
          if (data[i] < data[i - 1])
          {
             int tempVariable = data[i];
             data[i] = data[i - 1];
             data[i - 1] = tempVariable;
 
             isSorted = false;
 
          }
       }
 
       if (isSorted)
          break;
    }
 }

2:

 // another possibility
 static int[] BubbleSort(int[] nums)
 {
    boolean unsorted = true;
    while (unsorted)
    {
       unsorted = false;
       for (int i = nums.length - 1; i > 0; i--)
       {
          if (nums[i] < nums[i-1])
          {
             int temp = nums[i];
             nums[i] = nums[i-1];
             nums[i-1] = temp;
             unsorted = true;
          }
       }
    }
    return nums;
 }


Source(s): Bubble sort


JavaScript[edit]

JavaScript Implementation with simple HTML test page

<html>
<head>
<script type="text/javascript">
// GLOBAL FUNCTION
Array.prototype.bubble_sort = function() {
    var i, j;
    var swapped;
    var newarray = this.slice(0);
    var swap = function(j, k) {
      var temp = newarray[j];
      newarray[j] = newarray[k];
      newarray[k] = temp;
      return(true);
    }
    for(i=1; i<newarray.length; i++) {
      swapped = false;
      for(j=0; j<newarray.length - i; j++) {
        if (newarray[j+1] < newarray[j]) {
          swapped = swap(j, j+1);
        }
      }
      if (!swapped) break;
    }
    return(newarray)
}

// LOCAL FUNCTION
show = function (inarray, title) {
  document.writeln("<h4>"+title+":</h4>");
  document.writeln(inarray.join(", ")+"<br />");
} 
</script>
</head>
<body>
<script>
// MAIN
// test bubble_sort function
sorted_array = [1, 4, 7, 2, 1, 3, 2, 1, 4, 2, 3, 2, 1].bubble_sort();
show(sorted_array, "Sorted Array");
// result: [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 7]
</script>
</body>
</html> 
I just dont get this


Source(s): Bubble sort


Maya Embedded Language[edit]

global proc int[] SortList(int $list[])
{
	int $i;
	int $j;
	int $temp;
	int $flag;
	int $n = `size($list)`;

	for($i=$n-1; $i>0; $i--)
	{
		$flag = 1;
		for($j=0; $i>$j; $j++)
		{
			if($list[$j]>$list[$j+1])
			{
				$flag = 0;
				$temp = $list[$j];
				$list[$j] = $list[$j+1];
				$list[$j+1] = $temp;
			}
		}
		if($flag) {
			break;
		}
	}
	
	return $list;
}


Source(s): Bubble sort


MEL[edit]

 global proc int[] SortList(int $list[])
 {
 	int $i;
 	int $j;
 	int $temp;
 	int $flag;
 	int $n = `size($list)`;
 
 	for($i=$n-1; $i>0; $i--)
 	{
 		$flag = 1;
 		for($j=0; $i>$j; $j++)
 		{
 			if($list[$j]>$list[$j+1])
 			{
 				$flag = 0;
 				$temp = $list[$j];
 				$list[$j] = $list[$j+1];
 				$list[$j+1] = $temp;
 			}
 		}
 		if($flag) {
 			break;
 		}
 	}
 	
 	return $list;
 }


Source(s): Bubble sort


OCaml[edit]

When two adjacent elements are in the wrong order, reverse them and recurse:

let rec sweep = function
    h1 :: h2 :: t when h1 > h2 -> h2 :: sweep (h1 :: t)
  | h1 :: t -> h1 :: sweep t
  | [] -> [];;
let rec bubble l =
  let l' = sweep l in
    if l <> l' then bubble l'
               else l;;

For example:

# bubble [1;9;2;8;3;7;4;6;5];;
- : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9]


Source(s): Bubble sort


Pascal[edit]

Procedure BubbleSort:
const
MAXINTARRAY  : 1000; { Set this value to fit your data needs for max array size }
STARTINTARRAY  : 1; { Set 1 _or_ 0; indicates the lower index of the array }
Type
IntArray : Array[STARTINTARRAY..MAXINTARRAY] of integer;

BubbleSort is an all purpose sorting procedure that is passed an array of integers and returns that same array with the array elements sorted as desired.

Parameters are used to control the sorting operation:
If you want to sort the entire array, pass a value in Count that signals the number of elements you want sorted. BubbleSort will then sort Count number of elements starting with the first element in the array.

If you want to sort a subset of elements within the array, pass 0 in Count and pass a beginning and ending subset index number in First and Last, respectively.

The sort will be either ascending or decending as controlled by the parameter Acend:

Pass True in Acend and the sort will be ascending. Pass False and the sort will be decending.

  • Data: The array to be sorted.
  • NOTE: Sample is a var and will be modified by BubbleSort, unless the array is already in a sorted state.
  • Count: 0 _or_ the number of elements to be sorted, starting with the first element.
  • First: The first element to be sorted in a subset of the array.
  • Last: The last element to be sorted in a subset of the array.
  • Acend: Flag to indicate the sort order. True is ascending order. False is decending.
  • Succ: Flag returns result of BubbleSort
    • 0 = success.
    • 1 = Failed. Parameter First has value below allowed first index value.
    • 2 = Failed. Parameter Last has value above allowed last index value.
    • 3 = Failed. Parameter Last has value below allowed first index value.

 Procedure BubbleSort( 
                       Var Data : IntArray;
                       Count    : integer;
                       First    : integer;
                       Last     : integer;
                       Acend    : boolean;
                       Var Succ : integer );
 
 var 
   i,
   temp, 
   s_begin, 
   s_end,
   numsort : integer;
   sorted  : boolean;
 
 Begin
   { initialize for full array sort }
   s_begin := STARTINTARRAY;
   s_end   := STARTINTARRAY + count - 1 ;
   numsort := Count;
   Succ    := 0;    { assume success }
 
   { check for a subset sort; check parameters for correctness }
   if (Count = 0) then 
     Begin
       If (First < STARTINTARRAY) then 
       Begin { error: sort start index too low }
         Succ := 1;
         Exit;
       End;
       If (Last > MAXINTARRAY) then
       Begin { error: sort end index too high }
         Succ := 2;
         Exit;
       End;
       if (Last < STARTINTARRAY) then 
       Begin { error: sort end index too low }
         Succ := 3;
         Exit;
       End;
       s_begin := First;
       s_end   := Last;
       numsort := Last - First + 1;
     End;
   If numsort <= 1 then Exit; { only one element, so exit }
 
   If Acend then
   Begin { do the ascending sort }
     Repeat
       sorted := true; { flag default is true }
       For i := s_begin to s_end -1 do
         if (Data[i] < Data[i+1]) then
         Begin
           { swap contents of Data[i] and Data[i+1] }
           temp      := Data[i];
           Data[i]   := Data[i+1];
           Data[i+1] := temp;
           { set flag to indicate a swap occured; i.e., sort may not be completed }
           sorted := false;
         End;
     Until sorted;
   End Else
   Begin { do the descending sort }
     Repeat
       sorted := true; { flag default is true }
       For i := s_begin to s_end -1 do
         if (Data[i] < Data[i+1]) then
         Begin
           { swap contents of Data[i] and Data[i+1] }
           temp      := Data[i];
           Data[i]   := Data[i+1];
           Data[i+1] := temp;
           { set flag to indicate a swap occured; i.e., sort may not be completed }
           sorted := false;
         End;
     Until sorted;
   End;
 End;

A simplified version:

 Procedure BubbleSort(var a:IntArray; size:integer);
  var i,j,temp: integer;
  begin
   for i:=1 to size-1 do
    for j:=1 to size do
     if a[i]>a[j] then
        begin
         temp:=a[i]; a[i]:=a[j]; a[j]:=temp;
        end;
  end;


Source(s): Bubble sort


Perl[edit]

1:

sub bubbleSort {
    my @list   = @_;
    my $sorted = 0;

    while ( not $sorted ) {
        $sorted = 1; # Innocent until proven guilty.

        for my $current ( 1 .. $#list ) {
            my $previous = $current - 1;

            if ( $list[$current] < $list[$previous] ) {
                ($list[$current], $list[$previous]) = ($list[$previous], $list[$current]);

                $sorted = 0;
            }
        }
    }

    return @list;
}

my @unsorted = qw( 1 7 6 3 83 64 8281 0 38 1 );
my @sorted = bubbleSort(@unsorted);

2:

 sub bubble_sort {
     my @a = @_;
     for my $ii (0 .. $#a) {
         for my $jj ($ii + 1 .. $#a) {
             @a[$ii, $jj] = @a[$jj, $ii] if $a[$jj] < $a[$ii];
         };
     };
     return @a;
 };

 print bubble_sort qw(6 5 3 8 7 4);


Source(s): Bubble sort


PHP[edit]


 function bubbleSort ($items) {
     $size = count($items);
     for ($i=0; $i<$size; $i++) {
          for ($j=0; $j<$size-1-$i; $j++) {
               if ($items[$j+1] < $items[$j]) {
                   arraySwap($items, $j, $j+1);
               }
          }
     }
     return $items;
 }
 function arraySwap (&$arr, $index1, $index2) {
     list($arr[$index1], $arr[$index2]) = array($arr[$index2], $arr[$index1]);
 }


Source(s): Bubble sort


Progress ABL/4GL[edit]

FUNCTION BubbleSort RETURNS CHARACTER
  (INPUT pcArray AS CHARACTER): 
  
  DEFINE VARIABLE cTempArray AS CHARACTER NO-UNDO.
  DEFINE VARIABLE i          AS INTEGER   NO-UNDO.
  DEFINE VARIABLE j          AS INTEGER   NO-UNDO.
  DEFINE VARIABLE iEntries   AS INTEGER   NO-UNDO.

  iEntries = NUM-ENTRIES(pcArray).

  DO i = iEntries TO 1 BY -1:
    DO j = 1 TO i - 1:
      IF ENTRY(j, pcArray) > ENTRY(j + 1, pcArray) THEN
      DO:
        cTempArray            = ENTRY(j, pcArray).
        ENTRY(j, pcArray)     = ENTRY(j + 1, pcArray).
        ENTRY(j + 1, pcArray) = cTempArray.
      END.
    END.
  END.

  RETURN pcArray.

END FUNCTION.


Source(s): Bubble sort


Python[edit]

 def BubbleSort(lst):
     lst = list(lst) #copy collection to list 
     for passesLeft in range(len(lst)-1, 0, -1):
         for i in range(passesLeft):
             if lst[i] < lst[i + 1]:
                lst[i], lst[i + 1] = lst[i + 1], lst[i]
     return lst

Another method

 def BubbleSort2(lst):
     lst = list(lst)
     swapped = True
     while swapped:
         swapped = False
         for i in range(len(lst)-1):
             if lst[i] < lst[i+1]:
                 lst[i], lst[i+1] = lst[i+1], lst[i]
                 swapped = True
     return lst


Source(s): Bubble sort


QuickBASIC[edit]

CLS

DIM NameArray$(1000)

i = 0

' Seed read ...
READ Name$

' Loop through and read names in data ...
DO WHILE Name$ <> "*EOD"
      i = i + 1
      NameArray$(i) = Name$
      READ Name$
LOOP

' The value of i is now the number of names in the array ...
ArraySize = i


' Bubble (or ripple) sort ...
FOR i = 1 TO ArraySize - 1
  FOR j = 1 TO ArraySize - 1
      IF NameArray$(j) > NameArray$(j + 1) THEN
         SWAP NameArray$(j), NameArray$(j + 1)
      END IF
  NEXT j
NEXT i

' Print out the sorted results ...
FOR i = 1 TO ArraySize
        PRINT NameArray$(i)
NEXT i

DATA Crowe,
DATA Adams,
DATA Zimmerman,
DATA Goodhead,
DATA Smith,
DATA Jones,
DATA *EOD


Source(s): Bubble sort


Ruby[edit]

 def bubble_sort(list)
   list = list.dup   # we should not modify original list
   for i in 0...list.length
     for j in 0..(list.length - i - 2)
       list[j], list[j + 1] = list[j + 1], list[j]  if list[j + 1] < list[j]
     end
   end
   return list
 end


Source(s): Bubble sort


Scheme[edit]

1: Using a recursive procedure:

(define (bubble-sort vector key <<? ==?)
 (define (bubble-swap vector idx1 idx2)
   (let ((temp (vector-ref vector idx1)))
     (vector-set! vector idx1 (vector-ref vector idx2))
     (vector-set! vector idx2 temp)
     #t))
 (define (bubble-up outer-idx inner-idx has-changed)
   (if (<= inner-idx outer-idx)
       (bubble-up outer-idx
                  (+ inner-idx 1)
                  (if (<<? (key (vector-ref vector (+ inner-idx 1)))
                           (key (vector-ref vector inner-idx)))
                      (bubble-swap vector inner-idx (+ inner-idx 1))
                      has-changed))
       has-changed))
 (define (bubble-sort-iter unsorted-idx)
   (if (>= unsorted-idx 0)
       (if (bubble-up unsorted-idx 0 #f)
           (bubble-sort-iter (- unsorted-idx 1)))))
 (bubble-sort-iter (- (vector-length vector) 2)))

2: Using the do-loop:

(define (bubble-sort vector key <<? ==?)
 (define (bubble-swap vector idx1 idx2)
   (let ((temp (vector-ref vector idx1)))
     (vector-set! vector idx1 (vector-ref vector idx2))
     (vector-set! vector idx2 temp)
     #t))
 (do ((unsorted-idx (- (vector-length vector) 2) (- unsorted-idx 1)))
   ((or (< unsorted-idx 0)
        (not (do ((inner-idx
                   0
                   (+ inner-idx 1))
                  (has-changed
                   #f
                   (if (<<? (key (vector-ref vector (+ inner-idx 1)))
                            (key (vector-ref vector inner-idx)))
                       (bubble-swap vector inner-idx (+ inner-idx 1))
                       has-changed)))
               ((> inner-idx unsorted-idx) has-changed)
               '()))))
   '()))

3: Again using DO, but this time implementing the same algorithm as the Python code above, which is much simpler than the other Scheme examples.

(define (bubblesort! v)
  (do ((passes-left (- (vector-length v)
                       1)
                    (- passes-left 1)))
      ((= passes-left 0))
    (do ((index 0 (+ index 1)))
        ((= index (- (vector-length v)
                     1)))
      (if (< (vector-ref v index)
             (vector-ref v (+ index 1)))
          (vector-swap! v index (+ index 1)))))
  v)
;; VECTOR-SWAP! is available in SRFI 43.
;; If your Scheme system does not provide SRFI 43, here is a quick
;; definition:
(define (vector-swap! v i j)
  (let ((t (vector-ref v i)))
    (vector-set! v i (vector-ref v j))
    (vector-set! v j t)))

4: Written in a non-ugly way

(define (bubble-sort list)
  (define (swap index1 index2)
    (let ((item1 (list-ref list index1))
          (item2 (list-ref list index2)))
      (set-car! (list-tail list index1) item2)
      (set-car! (list-tail list index2) item1)))
  (let float ((index 0))
    (cond ((= (+ index 1) (length list)) list)
          ((< (list-ref list index)
              (list-ref list (+ index 1)))
           (float (+ index 1)))
          ((= (list-ref list index)
              (list-ref list (+ index 1)))
           (float (+ index 1)))
          (else
           (swap index (+ index 1))
           (float (if (= index 0) 0 (- index 1)))))))


Source(s): Bubble sort


Seed7[edit]

const proc: bubbleSort (inout array elemType: arr) is func
  local
    var boolean: swapped is FALSE;
    var integer: i is 0;
    var elemType: help is elemType.value;
  begin
    repeat
      swapped := FALSE;
      for i range 1 to length(arr) - 1 do
        if arr[i] > arr[i + 1] then
          help := arr[i];
          arr[i] := arr[i + 1];
          arr[i + 1] := help;
          swapped := TRUE;
        end if;
      end for;
    until not swapped;
  end func;

Original source: [1]


Source(s): Bubble sort


SWI-Prolog[edit]

bs(L,S) :-
    append(P, [A, B|T], L),
    B < A ->
        append(P, [B, A|T], R),
        bs(R, S)
    ; S = L.


Source(s): Bubble sort


TCL[edit]

  proc bubble_sort {a} {
    if {[llength $a] >= 2} {
      for {set i [expr [llength $a]-1]} {$i > 0} {incr i -1} {
        set has_swapped "FALSE"
        for {set j 0} {$j < $i} {incr j} {
          if {[lindex $a $j] > [lindex $a [expr $j + 1]]} {
            set temp [lindex $a $j]
            set a [lreplace $a $j $j [lindex $a [expr $j + 1]]]
            set a [lreplace $a [expr $j + 1] [expr $j + 1] $temp]
            set has_swapped "TRUE"
          }
        }
        if {$has_swapped == "FALSE"} {
          break
        }
      }
    }
    return $a
  }


Source(s): Bubble sort


Turbo Prolog[edit]

domains
	elem = integer
	list = elem*
predicates
	swapAll(list, list)
	isSorted(list)
	bubble(list, list)
clauses
	swapAll([H|[]], [H]):-!.
	swapAll([H1,H2|T], [H2|R]):-
		H1 > H2,
		!,
		swapAll([H1|T], R).
	swapAll([H|T], [H|R]):-
		swapAll(T, R).
	
	isSorted([]):-!. %list with no elements is sorted
	isSorted([_|[]]):-!. %list with 1 element is sorted
	isSorted([H1,H2|L]):-
		H1 < H2,
		isSorted([H2|L]).
	
	bubble(L, L):-
		isSorted(L), !.
	bubble(L, R):-
		swapAll(L, L2),
		bubble(L2, R).


Source(s): Bubble sort


Turing[edit]

var nombres, limit : int
get nombres
get limit
var g : int := 0
var last : int := limit
var sure : boolean := false
var rann : array 1 .. nombres of int
for i : 1 .. nombres
    rann (i) := Rand.Int (0, limit)
end for
loop
    for d : 1 .. nombres - 1
        if rann (d) > rann (d + 1) then
            g := rann (d)
            rann (d) := rann (d + 1)
            rann (d + 1) := g
            sure := false
        end if
    end for
    exit when sure
    sure := true
end loop
for b : 1 .. upper (rann)
    put " ", rann (b) ..
end for


Source(s): Bubble sort


VBA[edit]

 Option Base 1

 Private Sub bubble(N as integer, array() as integer)
  
 'N is the number of integers in the array'
  
 Dim I as Integer
 Dim J as Integer
 Dim P as Integer
 Dim Temp as Integer
 
 For I = n - 1 To 1 Step -1
     P=0
     For J = 1 To I
          If array(J) > array(J + 1) Then
             Temp = array(J)
             array(J) = array(J + 1)
             array(J + 1) = Temp
          Else
             P=P+1
          End If
          If P=I then GoTo premend
     Next J
 Next I
 
 'premend = premature ending = all integers are allready sorted'
 premend:
 
 End Sub


Source(s): Bubble sort


Visual Basic[edit]

 Sub Bubblesort(Array() as Integer, Length as Integer)
     Dim I As Integer
     Dim J As Integer
     Dim Temp As Integer
     Dim Length As Integer
     Dim Array() As String = {}

     For I = Length - 1 To 1 Step -1 'the last element on the array does not get sorted.  
         For J = 0 To I - 1
             If Array(J) > Array(J + 1) Then  ' Compare neighboring elements  
                 Temp = Array(J)
                 Array(J) = Array(J + 1)
                 Array(J + 1) = Temp

             End If
         Next
     Next
 End Sub

References & External Links[edit]


Source(s): Bubble sort