-
-
Notifications
You must be signed in to change notification settings - Fork 26
Sorting Algorithms #22
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
Draft
dlesnoff
wants to merge
18
commits into
TheAlgorithms:main
Choose a base branch
from
dlesnoff:insertion_sort
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 9 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
47901ec
Add insertion sort
dlesnoff 3da8127
Remove tests from insertion sort file
dlesnoff 7b59c70
And add those tests in an external file
dlesnoff 24328c7
And add those tests in an external file
dlesnoff c07308e
[testSort] Set verbose to false by default
dlesnoff 692e0ca
Add bubble sort
dlesnoff f1b8b46
Merge branch 'bubble_sort' into insertion_sort
dlesnoff 4d13803
Merge branch 'main' into insertion_sort
dlesnoff 2c971f2
Add titles in DIRECTORY.md
dlesnoff 98331f5
Add sharp for titles
dlesnoff 51570f2
Add comments and description of the quicksort algorithm
dlesnoff 30d00e4
Rename testSort.nim -> test_sorts.nim
dlesnoff 0ba7024
Fix tests in counting sort but ...
dlesnoff ca2237e
Remove counting sort
dlesnoff c76155d
Merge branch 'main' into insertion_sort
dlesnoff efb46e7
Merge branch 'main' into insertion_sort
dlesnoff ee6590e
Run nimpretty
dlesnoff 8e893ab
Merge branch 'main' into insertion_sort
dlesnoff File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
<!--- DO NOT EDIT: This file is automatically generated by `directory.nim` --> | ||
|
||
# The Algorithms — Nim: Directory Hierarchy | ||
|
||
## Dynamic Programming | ||
* [Catalan Numbers](dynamic_programming/catalan_numbers.nim) | ||
* [Viterbi](dynamic_programming/viterbi.nim) | ||
|
||
## Maths | ||
* [Area](maths/area.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) | ||
|
||
## Strings | ||
* [Check Anagram](strings/check_anagram.nim) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
# 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 ./testSort.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]) | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
## 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 ./testSort.nim | ||
|
||
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]) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ./testSort | ||
randomize() | ||
|
||
suite "Merge Sort": | ||
test "Integers": | ||
check testSort mergeSort[int] | ||
test "Float": | ||
check testSort mergeSort[float] | ||
test "Char": | ||
check testSort mergeSort[char] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
# Quick Sort | ||
## Add Description | ||
## TODO: Need an out of place version of the test | ||
## https://en.wikipedia.org/wiki/Shellsort | ||
## 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, the first element | ||
# let pivot = lo | ||
# More performant: choose at random!!! | ||
let pivot = rand(lo..hi) | ||
var | ||
i = lo + 1 | ||
j = hi | ||
|
||
# We place the pivot element at the | ||
# lowest position | ||
swap(list[lo], list[pivot]) | ||
var running = true | ||
while running: | ||
while list[i] <= list[lo] and i < hi: | ||
i += 1 | ||
while list[j] >= list[lo] and j > lo: | ||
j -= 1 | ||
if i < j: | ||
swap(list[i], list[j]) | ||
else: | ||
running = false | ||
swap(list[lo], list[j]) | ||
|
||
# Recursive calls | ||
quicksort(list, lo, j - 1) | ||
quicksort(list, j + 1, hi) | ||
|
||
|
||
proc quickSort*[T](list: var openArray[T]) = | ||
## Main function | ||
quicksort(list, list.low, list.high) | ||
|
||
|
||
proc QuickSort[T](list: openArray[T]): seq[T] = | ||
## Second quick sort implementation, out-of-place but making a lot of copies | ||
## Easier to memorize | ||
if len(list) == 0: | ||
return @[] | ||
var pivot = list[0] | ||
var left: seq[T] = @[] | ||
var right: seq[T] = @[] | ||
for i in low(list)..high(list): | ||
if list[i] < pivot: | ||
left.add(list[i]) | ||
elif list[i] > pivot: | ||
right.add(list[i]) | ||
result = QuickSort(left) & | ||
pivot & | ||
QuickSort(right) | ||
|
||
when isMainModule: | ||
import std/[unittest] | ||
import ./testSort | ||
randomize() | ||
|
||
suite "Quick Sort": | ||
test "Integers": | ||
check testSort quickSort[int] | ||
# check testSort QuickSort[int] | ||
test "Float": | ||
check testSort quickSort[float] | ||
test "Char": | ||
check testSort quickSort[char] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ./testSort | ||
randomize() | ||
|
||
suite "Selection Sort": | ||
test "Integers": | ||
check testSort selectionSort[int] | ||
test "Float": | ||
check testSort selectionSort[float] | ||
test "Char": | ||
check testSort selectionSort[char] |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.