Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sorting Algorithms #22

Draft
wants to merge 18 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,15 @@
* [Arc Length](maths/arc_length.nim)
* [Bitwise Addition](maths/bitwise_addition.nim)

## Sorts
* [Bubble sort](sorts/bubble_sort.nim)
dlesnoff marked this conversation as resolved.
Show resolved Hide resolved
* [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)
Expand All @@ -22,4 +31,3 @@

## Strings
* [Check Anagram](strings/check_anagram.nim)

78 changes: 78 additions & 0 deletions sorts/bubble_sort.nim
Original file line number Diff line number Diff line change
@@ -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])
51 changes: 51 additions & 0 deletions sorts/insertion_sort.nim
Original file line number Diff line number Diff line change
@@ -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])
62 changes: 62 additions & 0 deletions sorts/merge_sort.nim
Original file line number Diff line number Diff line change
@@ -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]
107 changes: 107 additions & 0 deletions sorts/quick_sort.nim
Original file line number Diff line number Diff line change
@@ -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]
29 changes: 29 additions & 0 deletions sorts/selection_sort.nim
Original file line number Diff line number Diff line change
@@ -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]
Loading
Loading