-
-
Notifications
You must be signed in to change notification settings - Fork 27
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 all 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
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 @@ | ||
## 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]) |
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,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]) |
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 test_sorts | ||
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,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] |
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 test_sorts | ||
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.
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.