diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cc694be --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +bin/* +*.o diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..b8d6031 --- /dev/null +++ b/Makefile @@ -0,0 +1,14 @@ +BINDIR := $(PWD)/bin +CFLAGS := -std=c99 -Wall -g + +export BINDIR CFLAGS + + +all: + cd src && $(MAKE) + +clean: + rm -f bin/* + + +.PHONY: all clean diff --git a/bench b/bench index c346b1a..08808c7 100755 --- a/bench +++ b/bench @@ -1,9 +1,10 @@ #!/bin/bash -SETUP="import sorting;import random;l = list(range(0, ${1-5000}));random.shuffle(l)" +SETUP="import sorting" +LIST="$(python -c "import random;l = list(range(0, ${1-5000}));random.shuffle(l);print(l)")" echo -n "insertion sort: " -python -m timeit -s "$SETUP" 'sorting.insertion_sort(l)' +python -m timeit -s "$SETUP" "sorting.insertion_sort($LIST)" echo -n "merge sort: " -python -m timeit -s "$SETUP" 'sorting.merge_sort(l)' +python -m timeit -s "$SETUP" "sorting.merge_sort($LIST)" diff --git a/bin/.keep b/bin/.keep new file mode 100644 index 0000000..e69de29 diff --git a/sorting.rb b/sorting.rb new file mode 100644 index 0000000..f4f68fd --- /dev/null +++ b/sorting.rb @@ -0,0 +1,12 @@ +def insertion_sort(a) + (0..(a.length - 1)).each do |j| + key = a[j] + i = j - 1 + while (i >= 0) && (a[i] > key) + a[i + 1] = a[i] + i = i - 1 + end + a[i + 1] = key + end +end + diff --git a/src/Makefile b/src/Makefile new file mode 100644 index 0000000..ae4a6d3 --- /dev/null +++ b/src/Makefile @@ -0,0 +1,8 @@ +all: $(BINDIR)/insertion-sort + + +$(BINDIR)/insertion-sort: insertion-sort.c + gcc -o $@ $(CFLAGS) $^ + + +.PHONY: all diff --git a/src/insertion-sort.c b/src/insertion-sort.c new file mode 100644 index 0000000..be8594a --- /dev/null +++ b/src/insertion-sort.c @@ -0,0 +1,38 @@ +#include + +void insertion_sort(int * a, int len_a); + + +int +main(int argc, char ** argv) +{ + int i; + int l[] = {1, 4, 8, 9, 2, 3}; + + insertion_sort(l, 6); + + for (i = 0; i < 6; i++) { + printf("%d\n", l[i]); + } +} + + +void +insertion_sort(int * a, int len_a) +{ + int i, j, key; + + for (j = 1; j < len_a; j++) { + key = a[j]; + i = j - 1; + while ((i >= 0) && (a[i] > key)) { + a[i + 1] = a[i]; + i = i - 1; + } + a[i + 1] = key; + } +} + + +/* vim:filetype=c + */ diff --git a/test_sorting.rb b/test_sorting.rb new file mode 100644 index 0000000..165012f --- /dev/null +++ b/test_sorting.rb @@ -0,0 +1,20 @@ +require 'sorting' + + +def test_insertion_sort + tmpl = [8, 2, 4, 9, 3, 6] + a = Array.copy(tmpl) + expected = [2, 3, 4, 6, 8, 9] + + insertion_sort(a) + + if expected != a + throw Exception.new 'OMG FAIL' + else + puts 'YAY!' + end + +end + + +test_insertion_sort