Skip to content

Commit fcd347c

Browse files
Merge pull request #696 from 5ar5kovic/master
Sorting Algorithms
2 parents e90fb03 + ce92384 commit fcd347c

File tree

98 files changed

+1808
-243
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

98 files changed

+1808
-243
lines changed

README.md

+18-12
Original file line numberDiff line numberDiff line change
@@ -165,18 +165,24 @@ ACM-ICPC Algorithms is a collection of important algorithms and data structures
165165
* [Ternary Search](/Search/TernarySearch)
166166
* [Interpolation Search](/Search/InterpolationSearch)
167167
* [Sorting Algorithms](/Sorting)
168-
* [Bubble Sort](/Sorting/bubble%20sort)
169-
* [Cocktail Shaker Sort](/Sorting/CocktailShakerSort)
170-
* [Counting Sort](/Sorting/CountingSort)
171-
* [Heap Sort](/Sorting/HeapSort)
172-
* [Index Sort](/Sorting/IndexSort)
173-
* [Insertion Sort](/Sorting/InsertionSort)
174-
* [Merge Sort](/Sorting/MergeSort)
175-
* [Pancake Sorting](/Sorting/Pancake%20sorting)
176-
* [Quick Sort](/Sorting/QuickSort)
177-
* [Radix Sort](/Sorting/RadixSort)
178-
* [Selection Sort](/Sorting/SelectionSort)
179-
* [Shell Sort](/Sorting/ShellSort)
168+
* [BogoSort](/Sorting/BogoSort)
169+
* [Bubble Sort](/Sorting/Bubble%20Sort)
170+
* [Bucket Sort](/Sorting/Bucket%20Sort)
171+
* [Cocktail Shaker Sort](/Sorting/Cocktail%20Shaker%20Sort)
172+
* [Comb Sort](/Sorting/Comb%20Sort)
173+
* [Counting Sort](/Sorting/Counting%20Sort)
174+
* [HeapSort](/Sorting/HeapSort)
175+
* [Index Sort](/Sorting/Index%20Sort)
176+
* [Insertion Sort](/Sorting/Insertion%20Sort)
177+
* [Merge Sort](/Sorting/Merge%20Sort)
178+
* [Pancake Sorting](/Sorting/Pancake%20Sorting)
179+
* [Patience Sorting](/Sorting/Patience%20Sorting)
180+
* [QuickSort](/Sorting/QuickSort)
181+
* [Radix Sort](/Sorting/Radix%20Sort)
182+
* [Selection Sort](/Sorting/Selection%20Sort)
183+
* [ShellSort](/Sorting/ShellSort)
184+
* [TimSort](/Sorting/TimSort)
185+
* [Topological Sorting](/Sorting/Topological%20Sorting)
180186
* [String Algorithms](/String)
181187
* [Anagram](/String/Anagram)
182188
* [Balanced Parenthesis](/String/Balanced%20Parentheses)

Sorting/BogoSort/Python/BogoSort.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import random
2+
import unittest
3+
4+
# returns the sorted version of the given array by
5+
# checking first if its sorted, and then if not
6+
# randomly shuffles elements in the given array
7+
# and recursivly calls itself with the newly
8+
# shuffled array as an arguement.
9+
def monkeySort(arr1):
10+
for i in range(1, len(arr1)):
11+
if arr1[i-1] > arr1[i]:
12+
random.shuffle(arr1)
13+
return monkeySort(arr1)
14+
return arr1
15+
16+
class testMonkeySort(unittest.TestCase):
17+
18+
def test_regular_arr(self):
19+
arrPractice = [3, 4, 2, 1 ,5]
20+
self.assertEqual(monkeySort(arrPractice), [1, 2, 3, 4, 5])
21+
22+
def test_same_arr(self):
23+
arrPractice = [1, 1, 1, 1, 1]
24+
self.assertEqual(monkeySort(arrPractice), arrPractice)
25+
26+
def test_empty_arr(self):
27+
arrPractice = []
28+
self.assertEqual(monkeySort(arrPractice), arrPractice)
29+
30+
def test_duplicate_arr(self):
31+
arrPractice = [4, 2, 2, 1, 1]
32+
arrSolution = [1, 1, 2, 2, 4]
33+
self.assertEqual(monkeySort(arrPractice), arrSolution)
34+
35+
if __name__ == "__main__":
36+
unittest.main()

Sorting/BogoSort/README.md

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<h1>BogoSort</h1>
2+
<p>In computer science, bogosort (also permutation sort, stupid sort, slowsort, shotgun sort or monkey sort) is a highly ineffective sorting function based on the generate and test paradigm. The function successively generates permutations of its input until it finds one that is sorted. It is not useful for sorting, but may be used for educational purposes, to contrast it with more efficient algorithms.</p>
3+
4+
<a href="https://en.wikipedia.org/wiki/Bogosort">Source: Wikipedia</a>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
>>,[>>,]<<[
2+
[<<]>>>>[
3+
<<[>+<<+>-]
4+
>>[>+<<<<[->]>[<]>>-]
5+
<<<[[-]>>[>+<-]>>[<<<+>>>-]]
6+
>>[[<+>-]>>]<
7+
]<<[>>+<<-]<<
8+
]>>>>[.>>]

Sorting/Bubble Sort/Go/Bubble_Sort.go

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
)
6+
7+
var toBeSorted [10]int = [10]int{1,3,2,4,8,6,7,2,3,0}
8+
9+
func bubbleSort(input [10]int) {
10+
// n is the number of items in our list
11+
n := 10
12+
swapped := true
13+
for swapped {
14+
swapped = false
15+
for i := 1; i < n-1; i++ {
16+
if input[i-1] > input[i] {
17+
fmt.Println("Swapping")
18+
// swap values using Go's tuple assignment
19+
input[i], input[i-1] = input[i-1], input[i]
20+
swapped = true
21+
}
22+
}
23+
}
24+
fmt.Println(input)
25+
}
26+
27+
28+
func main() {
29+
fmt.Println("Hello World")
30+
bubbleSort(toBeSorted)
31+
32+
}
+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
-- Bubble sort (also known as sinking sort) is a simple sorting algorithm that
2+
-- repeatedly steps through the list to be sorted, compares each pair of
3+
-- adjacent items and swaps them if they are in the wrong order. The pass
4+
-- through the list is repeated until no swaps are needed, which indicates that
5+
-- the list is sorted.
6+
7+
local function bubblesort(t)
8+
repeat
9+
local sorted = true
10+
for i=2, #t do
11+
if (t[i-1] > t[i]) then
12+
t[i-1], t[i] = t[i], t[i-1]
13+
sorted = false
14+
end
15+
end
16+
until sorted
17+
end
18+
19+
local numbers = {5, 1, 4, 2, 8}
20+
bubblesort(numbers)
21+
for _, number in ipairs(numbers) do
22+
print(number)
23+
end
+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
my @array = ( 5, 6, 3, 1, 7, 3, 2, 9, 10, 4 );
2+
3+
for my $x ( reverse 1 .. $#array ) {
4+
for my $y ( 0 .. $x - 1 ) {
5+
@array[ $y, $y + 1 ] = @array[ $y + 1, $y ]
6+
if $array[$y] > $array[ $y + 1 ];
7+
}
8+
}
9+
10+
print "@array\n";
File renamed without changes.
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
def bubble_sort(array)
2+
size = array.length
3+
for i in 0..(size-1)
4+
for j in 0..(size-2-i)
5+
if array[j] > array[j+1]
6+
array[j], array[j+1] = array[j+1], array[j]
7+
end
8+
end
9+
end
10+
end
11+
12+
# Dummy data for testing
13+
test_array = [7, 6, 5, 4, 3, 2, 1]
14+
# Display unsorted array
15+
puts "Unsorted Array:"
16+
puts test_array.join(' ')
17+
# Call heap sort on the array
18+
bubble_sort(test_array)
19+
# Display the sorted results
20+
puts "Post Bubble Sort"
21+
puts test_array.join(' ')
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import Foundation
2+
3+
var array = [5,3,4,6,8,2,9,1,7,10,11]
4+
var sortedArray = NSMutableArray(array: array)
5+
6+
var sortedAboveIndex = array.count
7+
do {
8+
var lastSwapIndex = 0
9+
for ( var i = 1; i < sortedAboveIndex; i++ ) {
10+
if (sortedArray[i - 1].integerValue > sortedArray[i].integerValue) {
11+
sortedArray.exchangeObjectAtIndex(i, withObjectAtIndex: i-1)
12+
lastSwapIndex = i
13+
}
14+
}
15+
sortedAboveIndex = lastSwapIndex
16+
17+
} while (sortedAboveIndex != 0)
18+
19+
println(array)
20+
21+
println(sortedArray as Array)

Sorting/Bubble Sort/desktop.ini

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
[ViewState]
2+
Mode=
3+
Vid=
4+
FolderType=Generic
+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <algorithm>
4+
5+
using namespace std;
6+
7+
8+
void bucketSort(float a[], int n)
9+
{
10+
vector<float> t[n];
11+
12+
for (int i=0; i<n; i++)
13+
{
14+
int x = n*a[i];
15+
t[x].push_back(a[i]);
16+
}
17+
18+
for (int i=0; i<n; i++)
19+
sort(t[i].begin(), t[i].end());
20+
21+
int k= 0;
22+
for (int i = 0; i < n; i++)
23+
for (int j = 0; j < t[i].size(); j++)
24+
a[k++] = t[i][j];
25+
}
26+
27+
int main()
28+
{
29+
float a[] = {0.765, 0.324, 0.111, 0.951, 0.245, 0.48};
30+
int n = sizeof(a)/sizeof(a[0]);
31+
cout << "Elements before Sorting\n";
32+
for (int i=0; i<n; i++)
33+
cout << a[i] << " ";
34+
35+
bucketSort(a, n);
36+
37+
cout << "\nElements After Sorting \n";
38+
for (int i=0; i<n; i++)
39+
cout << a[i] << " ";
40+
return 0;
41+
}
+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import java.util.*;
2+
//O(nlogn)
3+
public class BucketSort{
4+
5+
public static void bucketSort(int[] a) {
6+
int maxVal=a[0];
7+
for(int i=0;i<a.length;i++){
8+
if(a[i]>maxVal){
9+
maxVal=a[i];
10+
}
11+
}
12+
int [] bucket=new int[maxVal+1];
13+
14+
System.out.println("\n");
15+
for (int i=0; i<a.length; i++) {
16+
bucket[a[i]]++;
17+
//System.out.print(bucket[a[i]-1]);
18+
}
19+
20+
int outPos=0;
21+
for (int i=0; i<bucket.length; i++) {
22+
if(bucket[i]!=0){
23+
for (int j=0; j<bucket[i]; j++) {
24+
a[outPos++]=i;
25+
System.out.println(bucket[i]);
26+
}
27+
}
28+
}
29+
}
30+
31+
32+
33+
public static void main(String[] args) {
34+
int [] data= {10,23,53,22,1,1,100,32,58,34,42,64};
35+
36+
System.out.println("Before: " + Arrays.toString(data));
37+
bucketSort(data);
38+
System.out.println("After: " + Arrays.toString(data));
39+
}
40+
}

Sorting/Bucket Sort/README.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<h1>Bucket Sort</h1>
2+
<p>Bucket sort, or bin sort, is a sorting algorithm that works by distributing the elements of an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm. It is a distribution sort, a generalization of pigeonhole sort, and is a cousin of radix sort in the most-to-least significant digit flavor. Bucket sort can be implemented with comparisons and therefore can also be considered a comparison sort algorithm. The computational complexity estimates involve the number of buckets.</p>
3+
<img src="https://upload.wikimedia.org/wikipedia/commons/5/54/Sorting_bubblesort_anim.gif">
4+
5+
<a href="https://en.wikipedia.org/wiki/Bucket_sort">Source: Wikipedia</a>
+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<h1>Cocktail Shaker Sort</h1>
2+
<p>Cocktail shaker sort, also known as bidirectional bubble sort, cocktail sort, shaker sort (which can also refer to a variant of selection sort), ripple sort, shuffle sort, or shuttle sort, is a variation of bubble sort that is both a stable sorting algorithm and a comparison sort. The algorithm differs from a bubble sort in that it sorts in both directions on each pass through the list. This sorting algorithm is only marginally more difficult to implement than a bubble sort, and solves the problem of turtles in bubble sorts. It provides only marginal performance improvements, and does not improve asymptotic performance; like the bubble sort, it is not of practical interest (insertion sort is preferred for simple sorts), though it finds some use in education.</p>
3+
4+
<img src="https://upload.wikimedia.org/wikipedia/commons/e/ef/Sorting_shaker_sort_anim.gif">
5+
6+
<a href="https://en.wikipedia.org/wiki/Bubble_sort">Source: Wikipedia</a>

Sorting/CocktailShakerSort/README.md

-15
This file was deleted.

Sorting/Comb Sort/README.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<h1>Comb Sort</h1>
2+
<p>Comb sort is a relatively simple sorting algorithm originally designed by Włodzimierz Dobosiewicz in 1980. Later it was rediscovered by Stephen Lacey and Richard Box in 1991. Comb sort improves on bubble sort.</p>
3+
<img src="https://upload.wikimedia.org/wikipedia/commons/4/46/Comb_sort_demo.gif">
4+
5+
<a href="https://en.wikipedia.org/wiki/Comb_sort">Source: Wikipedia</a>

Sorting/Comb Sort/Ruby/Comb_Sort.rb

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Comb Sort is mainly an improvement over Bubble Sort. Bubble sort always
2+
# compares adjacent values. So all inversions are removed one by one. Comb Sort
3+
# improves on Bubble Sort by using gap of size more than 1. The gap starts with
4+
# a large value and shrinks by a factor of 1.3 in every iteration until it
5+
# reaches the value 1. Thus Comb Sort removes more than one inversion counts
6+
# with one swap and performs better than Bublle Sort.
7+
#
8+
# More on: https://www.geeksforgeeks.org/comb-sort/
9+
# Illustration gif: https://upload.wikimedia.org/wikipedia/commons/4/46/Comb_sort_demo.gif
10+
11+
def combsort(array, shrink = 1.247330950103979)
12+
sorted = array.dup
13+
gap = array.size
14+
swapped = false
15+
16+
until gap == 1 && !swapped
17+
gap = (gap / shrink).to_i
18+
gap = 1 if gap < 1
19+
20+
swapped = false
21+
22+
gap.upto(sorted.size - 1) do |i|
23+
next if sorted[i - gap] <= sorted[i]
24+
25+
sorted[i - gap], sorted[i] = sorted[i], sorted[i - gap]
26+
swapped = true
27+
end
28+
end
29+
30+
sorted
31+
end
32+
33+
# Test case
34+
if $PROGRAM_NAME == __FILE__
35+
unsorted = Array.new(20) { rand(10_000) }
36+
sorted = combsort(unsorted)
37+
puts "Sorting: #{unsorted}"
38+
puts "Sorted: #{sorted}"
39+
puts "Correct? #{sorted == unsorted.sort}"
40+
end
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
function countingSort(arr, min, max)
2+
{
3+
var i, z = 0, count = [];
4+
5+
for (i = min; i <= max; i++) {
6+
count[i] = 0;
7+
}
8+
9+
for (i=0; i < arr.length; i++) {
10+
count[arr[i]]++;
11+
}
12+
13+
for (i = min; i <= max; i++) {
14+
while (count[i]-- > 0) {
15+
arr[z++] = i;
16+
}
17+
}
18+
return arr;
19+
}

Sorting/Counting Sort/README.md

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<h1>Counting Sort</h1>
2+
<p>In computer science, counting sort is an algorithm for sorting a collection of objects according to keys that are small integers; that is, it is an integer sorting algorithm. It operates by counting the number of objects that have each distinct key value, and using arithmetic on those counts to determine the positions of each key value in the output sequence. Its running time is linear in the number of items and the difference between the maximum and minimum key values, so it is only suitable for direct use in situations where the variation in keys is not significantly greater than the number of items. However, it is often used as a subroutine in another sorting algorithm, radix sort, that can handle larger keys more efficiently.</p>
3+
4+
<a href="https://en.wikipedia.org/wiki/Counting_sort">Source: Wikipedia</a>

0 commit comments

Comments
 (0)