futzing around with C and Ruby implementations

This commit is contained in:
Dan Buch 2011-08-17 23:07:18 -04:00
parent c8d657d3c1
commit 43db7108aa
8 changed files with 98 additions and 3 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
bin/*
*.o

14
Makefile Normal file
View File

@ -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

7
bench
View File

@ -1,9 +1,10 @@
#!/bin/bash #!/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: " 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: " echo -n "merge sort: "
python -m timeit -s "$SETUP" 'sorting.merge_sort(l)' python -m timeit -s "$SETUP" "sorting.merge_sort($LIST)"

0
bin/.keep Normal file
View File

12
sorting.rb Normal file
View File

@ -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

8
src/Makefile Normal file
View File

@ -0,0 +1,8 @@
all: $(BINDIR)/insertion-sort
$(BINDIR)/insertion-sort: insertion-sort.c
gcc -o $@ $(CFLAGS) $^
.PHONY: all

38
src/insertion-sort.c Normal file
View File

@ -0,0 +1,38 @@
#include <stdio.h>
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
*/

20
test_sorting.rb Normal file
View File

@ -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