Sorting algorithms/Bubble sort: Difference between revisions

→‎{{header|CMake}}: Reach O(n**2). Old code was closer to O(n**3).
(→‎{{header|CMake}}: Add 12th CMake example -- but only for lists of integers.)
(→‎{{header|CMake}}: Reach O(n**2). Old code was closer to O(n**3).)
Line 420:
<lang cmake># bubble_sort(var [value1 value2...]) sorts a list of integers.
function(bubble_sort var)
math(EXPR last "${lastARGC} - 1") # Prepare to sort # ARGV[1]..ARGV[last = last index of ARGN].
list(LENGTH ARGN last)
math(EXPR last "${last} - 1") # last = last index of ARGN
set(again YES)
while(again)
set(again NO)
math(EXPR last "${last} - 1") # Decrement last index.
foreach(index RANGE 01 ${last}) # Loop for each index.
math(EXPR index_plus_1 "${index} + 1")
listset(GET ARGNa "${ARGV${index} a}") # a = ARGNARGV[index]
listset(GET ARGNb "${ARGV${index_plus_1} b}") # b = ARGNARGV[index + 1]
if(a GREATER "${b}") # If a > b...
listset(REMOVE_AT ARGNARGV${index} "${index_plus_1b}") # ...then swap a and, b
listset(INSERT ARGN ARGV${indexindex_plus_1} "${ba}") # inside ARGNARGV.
set(again YES)
endif()
endforeach(index)
endwhile()
 
set(${var} "${ARGN}" PARENT_SCOPE)
set(answer)
math(EXPR last "${ARGC} - 1")
foreach(index RANGE 1 "${last}")
list(APPEND answer "${ARGV${index}}")
endforeach(index)
set("${var}" "${ARGNanswer}" PARENT_SCOPE)
endfunction(bubble_sort)</lang>
 
Anonymous user