How to resolve the algorithm Sorting Algorithms/Circle Sort step by step in the Nim programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sorting Algorithms/Circle Sort step by step in the Nim programming language
Table of Contents
Problem Statement
Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sorting Algorithms/Circle Sort step by step in the Nim programming language
Source code in the nim programming language
proc innerCircleSort[T](a: var openArray[T], lo, hi, swaps: int): int =
var localSwaps: int = swaps
var localHi: int = hi
var localLo: int = lo
if localLo == localHi:
return swaps
var `high` = localHi
var `low` = localLo
var mid = (localHi - localLo) div 2
while localLo < localHi:
if a[localLo] > a[localHi]:
swap a[localLo], a[localHi]
inc localSwaps
inc localLo
dec localHi
if localLo == localHi:
if a[localLo] > a[localHi + 1]:
swap a[localLo], a[localHi + 1]
inc localSwaps
localswaps = a.innerCircleSort(`low`, `low` + mid, localSwaps)
localSwaps = a.innerCircleSort(`low` + mid + 1, `high`, localSwaps)
result = localSwaps
proc circleSort[T](a: var openArray[T]) =
while a.innerCircleSort(0, a.high, 0) != 0:
discard
var arr = @[@[6, 7, 8, 9, 2, 5, 3, 4, 1],
@[2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1]]
for i in 0..arr.high:
echo "Original: ", $arr[i]
arr[i].circleSort()
echo "Sorted: ", $arr[i], if i != arr.high: "\n" else: ""
You may also check:How to resolve the algorithm Rare numbers step by step in the J programming language
You may also check:How to resolve the algorithm Reverse words in a string step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Sieve of Eratosthenes step by step in the 6502 Assembly programming language
You may also check:How to resolve the algorithm Abbreviations, automatic step by step in the V (Vlang) programming language
You may also check:How to resolve the algorithm Loops/Break step by step in the R programming language