# Source URL: https://dev.epicgames.com/community/snippets/zbLB/fortnite-bubble-sort
# Local doc: epic-docs/community/snippets/zbLB/fortnite-bubble-sort.md
# A simple sorting algorithm that steps through the array element by element,
# comparing and swapping two elements if they're not in order.
# When no swaps are done, then the list is sorted.
BubbleSort<public>(Array:[]t, Compare(L:t, R:t)<decides><transacts>:t where t:subtype(comparable))<transacts>:[]t=
Length:int = Array.Length
var OrderedArray:[]t = Array
# Iterate through the whole array.
for:
FirstIndex := 0..Length - 1
do:
# Tracking if any swaps were performed.
var DidSwap:logic = false
# Go element by element and compare adjacent elements.
# Largest elements will "bubble up" to the end first,
# so can ignore as many elements at the end as we've already checked.
for:
SecondIndex := 0..Length - FirstIndex - 1
not Compare[OrderedArray[SecondIndex], OrderedArray[SecondIndex + 1]]
ArrayWithSwappedElements := OrderedArray.Swap[SecondIndex, SecondIndex + 1]
do:
set OrderedArray = ArrayWithSwappedElements
set DidSwap = true
# If no swaps were performed, then the list is sorted.
# Return the array early.
if (not DidSwap?):
return OrderedArray
OrderedArray
Verse Library
verse
01 Snippet
Implements a standard bubble sort algorithm for sorting arrays, with an optional comparison function for custom ordering.
extracted-snippets/community/snippets/zbLB/fortnite-bubble-sort/01-snippet.verse
Sign in free to read the full source 🌴
This Verse Library file is members-only. Create a free account to view the complete source and download the .verse file.