diff --git a/DIRECTORY.md b/DIRECTORY.md index 3a46fe67..ed946373 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -13,6 +13,15 @@ * [Arc Length](maths/arc_length.nim) * [Bitwise Addition](maths/bitwise_addition.nim) +## Sorts + * [Bubble sort](sorts/bubble_sort.nim) + * [Insertion Sort](sorts/insertion_sort.nim) + * [Merge Sort](sorts/merge_sort.nim) + * [Quick Sort](sorts/quick_sort.nim) + * [Selection Sort](sorts/selection_sort.nim) + * [Shell Sort](sorts/shell_sort.nim) + * [Test sorting algorithms](sorts/testSort.nim) + ## Searches * [Binary Search](searches/binary_search.nim) * [Linear Search](searches/linear_search.nim) @@ -22,4 +31,3 @@ ## Strings * [Check Anagram](strings/check_anagram.nim) - diff --git a/sorts/bubble_sort.nim b/sorts/bubble_sort.nim new file mode 100644 index 00000000..50c6c60b --- /dev/null +++ b/sorts/bubble_sort.nim @@ -0,0 +1,78 @@ +## Bubble Sort +#[ +Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the input list element by element, comparing the current element with the one after it, swapping their values if needed. These passes through the list are repeated until no swaps had to be performed during a pass, meaning that the list has become fully sorted. +# https://en.wikipedia.org/wiki/Bubble_sort +]# + +func bubbleSort[T](l: var openArray[T]) = + let n = l.len + for i in countDown(n - 1, 1): + for j in 0 ..< i: + if l[j] > l[j+1]: + swap(l[j], l[j+1]) + + +func bubbleSortOpt1[T](l: var openArray[T]) = + let n = l.len + for i in countDown(n - 1, 1): + var flag: bool = true # Optimisation + for j in 0 ..< i: + if l[j] > l[j+1]: + flag = false + swap(l[j], l[j+1]) + if flag: # We can return/break early + return + +func bubbleSortWhileLoop[T](l: var openArray[T]) = + ## The same optimization can be rewritten with + ## a while loop + let n = l.len + var swapped = true + while swapped: + swapped = false + for i in 1 ..< n: + if l[i-1] > l[i]: + swap l[i-1], l[i] + swapped = true + +func bubbleSortOpt2[T](l: var openArray[T]) = + ## The n-th pass finds the n-th largest element + ## So no need to look at the n last elements + ## during the (n+1)-th pass + var + n = l.len + swapped = true + while swapped: + swapped = false + for i in 1 ..< n: + if l[i-1] > l[i]: + swap l[i-1], l[i] + swapped = true + dec n + +when isMainModule: + import std/[unittest, random] + import ./test_sorts.nim + randomize() + + suite "Insertion Sort": + test "Sort": + check testSort(bubbleSort[int]) + check testSort(bubbleSortOpt1[int]) + check testSort(bubbleSortWhileLoop[int]) + check testSort(bubbleSortOpt2[int]) + test "Sort with limit 10": + check testSort(bubbleSort[int], 15, 10) + check testSort(bubbleSortOpt1[int], 15, 10) + check testSort(bubbleSortWhileLoop[int], 15, 10) + check testSort(bubbleSortOpt2[int], 15, 10) + test "Sort with floating-point numbers": + check testSort(bubbleSort[float]) + check testSort(bubbleSortOpt1[float]) + check testSort(bubbleSortWhileLoop[float]) + check testSort(bubbleSortOpt2[float]) + test "Sort characters": + check testSort(bubbleSort[char]) + check testSort(bubbleSortOpt1[char]) + check testSort(bubbleSortWhileLoop[char]) + check testSort(bubbleSortOpt2[char]) diff --git a/sorts/insertion_sort.nim b/sorts/insertion_sort.nim new file mode 100644 index 00000000..3595e360 --- /dev/null +++ b/sorts/insertion_sort.nim @@ -0,0 +1,51 @@ +## Insertion Sort +## +## This algorithm sorts a collection by comparing adjacent elements. +## When it finds that order is not respected, it moves the element compared +## backward until the order is correct. It then goes back directly to the +## element's initial position resuming forward comparison. +## +## https://en.wikipedia.org/wiki/Insertion_sort + +import std/[random] + +func insertionSortAllSwaps[T](l: var openArray[T]) = + ## First implementation swaps elements until the right position is found + var i = 1 + while i < len(l): + var + j = i + while j > 0 and l[j-1] > l[j]: + swap(l[j], l[j-1]) + j = j - 1 + i = i + 1 + +func insertionSort[T](l: var openArray[T]) = + ## Sort your array similar to how you would sort your cards in your hand. + ## You take a card `key` and insert it in the right position in your hand one + ## at a time. + for j in 1 .. l.high: + var + key = l[j] + i = j - 1 + while i >= 0 and l[i] > key: + l[i+1] = l[i] + i.dec + l[i+1] = key + +when isMainModule: + randomize() + import std/unittest + import test_sorts + + suite "Insertion Sort": + test "Sort": + check testSort(insertionSortAllSwaps[int]) + check testSort(insertionSort[int]) + test "Sort with limit 10": + check testSort(insertionSortAllSwaps[int], 15, 10) + check testSort(insertionSort[int], 15, 10) + test "Sort with floating-point numbers": + check testSort(insertionSort[float]) + test "Sort characters": + check testSort(insertionSort[char]) diff --git a/sorts/merge_sort.nim b/sorts/merge_sort.nim new file mode 100644 index 00000000..da198352 --- /dev/null +++ b/sorts/merge_sort.nim @@ -0,0 +1,62 @@ +## Merge Sort +## Add Description +{.push raises: [].} + +# TODO: proc mergeSort[T](l: var openArray[T]) = +proc merge[T](list: var openArray[T], p, q, r: Natural) = + ## Merge two lists that have been sorted + ## Assumes all elements of `list` are less than + ## or equal to (T.high - 1) ! + let + n1 = q - p + 1 + n2 = r - q + var + L = newSeq[T](n1 + 1) + R = newSeq[T](n2 + 1) + for i in 0 ..< n1: + L[i] = list[p + i] + for j in 0 ..< n2: + R[j] = list[q + j + 1] + L[n1] = T.high + R[n2] = T.high + var + i = 0 + j = 0 + for k in p .. r: + if L[i] <= R[j]: + list[k] = L[i] + i.inc + else: + list[k] = R[j] + j.inc + + +proc mergeSort[T](list: var openArray[T], first, last: Natural) = + ## Division step + ## We split the list in two equal parts and work + ## separately on each of them + if first < last: + let half = (first + last) div 2 + mergeSort(list, first, half) + mergeSort(list, half + 1, last) + merge(list, first, half, last) + + +func mergeSort[T](list: var openArray[T]) = + ## Top level procedure + ## O(n * log(n)) in average complexity where n = l.len + mergeSort(list, list.low, list.high) + + +when isMainModule: + import std/[unittest, random] + import test_sorts + randomize() + + suite "Merge Sort": + test "Integers": + check testSort mergeSort[int] + test "Float": + check testSort mergeSort[float] + test "Char": + check testSort mergeSort[char] diff --git a/sorts/quick_sort.nim b/sorts/quick_sort.nim new file mode 100644 index 00000000..f63a47a7 --- /dev/null +++ b/sorts/quick_sort.nim @@ -0,0 +1,107 @@ +## Quick Sort +## +## The Quick Sort is the first sort algorithm with a complexity less than quadratic +## and even reaching the optimal theoretical bound of a sorting algorithm. +## +## As a strategy, it selects an element (the pivot) which serves as +## a separation barrier. We put all elements higher than the pivot to its right, +## and all elements lower than the pivot to its left. +## We can operate recursively on the lists on each side. The base cases are lists +## of one or two elements (elements on the left and the right of the pivot are +## trivially sorted). +## +## complexity: O(n*log(n)) +## https://en.wikipedia.org/wiki/Quicksort +## https://github.com/ringabout/data-structure-in-Nim/blob/master/sortingAlgorithms/quickSort.nim +{.push raises: [].} + +import std/random + +proc quickSort[T](list: var openArray[T], lo: int, hi: int) = + ## Quick Sort chooses a pivot element against which other + ## elements will be compared + if lo >= hi: + return + # Pivot selection + # Historically, developers used the first element as pivot + # let pivot = lo + # The best choice is to select at random the pivot! + let pivot = rand(lo..hi) + var + i = lo + 1 + j = hi + + # We place temporarily the pivot element at the + # lowest position + swap(list[lo], list[pivot]) + var running = true + + # We do not know in advance the number of swaps to do + while running: + # Starting from the left, we select the first element that is superior to the pivot and ... + while list[i] <= list[lo] and i < hi: + i += 1 + # starting from the right, the first element that is inferior to the pivot. + while list[j] >= list[lo] and j > lo: + j -= 1 + # We swap them if they are not in increasing order + if i < j: + swap(list[i], list[j]) + # If no swaps have been done, all elements are positioned correctly + # compared to the pivot, so we can exit the loop + # If the pivot is the maximum then i=hi(=j) so we do not swap and + # end the loop directly. + else: + running = false + # If all elements are strictly superior to the pivot (i=lo+1, j=lo)(we selected the minimum!), we make two pass, one swapping the second element with the pivot, and one placing the pivot at the beginning again. + # The pivot element is actually the (j − lo + 1)-th smallest element of the sublist, since we found (i − lo) = (j - lo + 1) elements smaller than it, and all other elements are larger. + swap(list[lo], list[j]) + + # Recursive calls - the whole list is sorted if and only if + # both the upper and lower parts are sorted. + quicksort(list, lo, j - 1) + quicksort(list, j + 1, hi) + + +proc quickSort*[T](list: var openArray[T]) = + ## Main function of the first quick sort implementation + quicksort(list, list.low, list.high) + + +proc QuickSort[T](list: openArray[T]): seq[T] = + ## Second quick sort implementation, out-of-place, making a lot of copies + if len(list) == 0: + return @[] + # We select the first element for simplicity + var pivot = list[0] + # We explicitely create the left and right lists. + + # We can not guess the length in advance, so we have to use + # a container on the heap. + var left: seq[T] = @[] + var right: seq[T] = @[] + + # If elements have the same value as the pivot, they are omitted! + for i in low(list)..high(list): + if list[i] < pivot: + left.add(list[i]) + elif list[i] > pivot: + right.add(list[i]) + + # We concatenate the results + result = QuickSort(left) & + pivot & + QuickSort(right) + +when isMainModule: + import std/[unittest] + import test_sorts + randomize() + + suite "Quick Sort": + test "Integers": + check testSort quickSort[int] + test "Float": + check testSort quickSort[float] + test "Char": + check testSort quickSort[char] diff --git a/sorts/selection_sort.nim b/sorts/selection_sort.nim new file mode 100644 index 00000000..92b77fb3 --- /dev/null +++ b/sorts/selection_sort.nim @@ -0,0 +1,29 @@ +## Selection Sort +## Add description +{.push raises: [].} + +func selectionSort[T](l: var openArray[T]) = + let n = l.len + for i in 0 .. n-2: + var + mini = l[i] + idx_min = i + for j in i ..< n: + if l[j] < mini: + mini = l[j] + idx_min = j + if idx_min != i: + swap(l[idx_min], l[i]) + +when isMainModule: + import std/[unittest, random] + import test_sorts + randomize() + + suite "Selection Sort": + test "Integers": + check testSort selectionSort[int] + test "Float": + check testSort selectionSort[float] + test "Char": + check testSort selectionSort[char] diff --git a/sorts/shell_sort.nim b/sorts/shell_sort.nim new file mode 100644 index 00000000..045ae544 --- /dev/null +++ b/sorts/shell_sort.nim @@ -0,0 +1,74 @@ +## Shell Sort +#[ +Shellsort, also known as Shell sort or Shell's method, +is an in-place comparison sort. It can be seen as either a generalization +of sorting by exchange (bubble sort) or sorting by insertion +(insertion sort). +Shell sort is: +- unstable +- adaptive (executes faster when the input is partially sorted +- Its time complexity is an open problem +References: +https://en.wikipedia.org/wiki/Shellsort +https://github.com/ringabout/data-structure-in-Nim/blob/master/sortingAlgorithms/shellSort.nim +]# +{.push raises: [].} + +func shell2Sort[T](list: var openarray[T]) = + var h = list.len + while h > 0: + h = h div 2 + for i in h ..< list.len: + let k = list[i] + var j = i + while j >= h and k < list[j-h]: + list[j] = list[j-h] + j -= h + list[j] = k + + +func shell3Sort*[T](x: var openArray[T]) = + ## https://github.com/ringabout/data-structure-in-Nim/blob/master/shellSort.nim + let length = len(x) + var size = 1 + while size < length: + size *= 3 + 1 + while size >= 1: + for i in size ..< length: + let temp = x[i] + for j in countdown(i, size, size): + if x[j - size] > temp: + x[j] = x[j - size] + else: + x[j] = temp + break + size = size div 3 + + +func shellSort[T](list: var openArray[T]) = + ## A gap of 1 is an insertion sort algorithm + ## Optimal gap sequence is referenced here: https://oeis.org/A102549 + const gaps = [701, 301, 132, 57, 23, 10, 4, 1] # Ciura gap sequence + for gap in gaps: + for i in gap .. list.high: + var + temp = list[i] + j = i + while (j >= gap and list[j - gap] > temp): + list[j] = list[j - gap] + j.dec gap + list[j] = temp + + +when isMainModule: + import std/[unittest, random] + import ./testSort + randomize() + + suite "Shell Sort": + test "Integers": + check testSort shellSort[int] + test "Float": + check testSort shellSort[float] + test "Char": + check testSort shellSort[char] diff --git a/sorts/test_sorts.nim b/sorts/test_sorts.nim new file mode 100644 index 00000000..0e74fe29 --- /dev/null +++ b/sorts/test_sorts.nim @@ -0,0 +1,26 @@ +## Test sorting algorithms +import std/[sequtils, random, algorithm] + +proc testSort*[T: SomeNumber](mySort: proc (x: var openArray[T]), + size: Positive = 15, + limit: SomeNumber = 100, verbose = false): bool = + ## Test the sort function with a random array + var limit = T(limit) + var arr = newSeqWith(size, rand(limit)) + if verbose: + echo "Before: ", arr + mySort(arr) + if verbose: + echo "After: ", arr + isSorted(arr) + +proc testSort*(mySort: proc (x: var openArray[char]), size: Positive = 15, + limit: char = 'z', verbose = false): bool = + ## Test the sort function with a random array + var arr = newSeqWith[char](size, rand('a' .. limit)) + if verbose: + echo "Before: ", arr + mySort(arr) + if verbose: + echo "After: ", arr + isSorted(arr)