futzing around with C and Ruby implementations
This commit is contained in:
parent
c8d657d3c1
commit
43db7108aa
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
bin/*
|
||||
*.o
|
14
Makefile
Normal file
14
Makefile
Normal 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
7
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)"
|
||||
|
12
sorting.rb
Normal file
12
sorting.rb
Normal 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
8
src/Makefile
Normal 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
38
src/insertion-sort.c
Normal 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
20
test_sorting.rb
Normal 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
|
Loading…
Reference in New Issue
Block a user