/* Bubble sort in Picat. Inspired by the SETL procedure in http://www.settheory.com/Chapters/Chapter_4.html This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ % import util. % import cp. main => go. go => _ = random2(), T2 = [random(1,300) : _ in 1..300], T2 := bubble_sort(T2), print(T2), nl. bubble_sort(T) = Ret => T2 = copy_term(T), Len = T.length, Check = true, while(Check = true) Swapped = false, foreach(I in 2..Len) if T2[I-1] > T2[I] then T2 := swap(T2,I-1,I), Swapped := true % interchange the items. end end, if Swapped = false then Check := false end end, Ret = T2. % % Swap position I <=> J in list L % swap(L,I,J) = L2, list(L) => L2 = copy_term(L), T = L2[I], L2[I] := L2[J], L2[J] := T.