Created
June 15, 2014 11:21
-
-
Save shosanna/e8d69d7c17c24e5e4920 to your computer and use it in GitHub Desktop.
This file contains 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
# Setup | |
array = [4, 2, 7, 11, 8, 24, 1, 0, 15, 33, 19, 21, 25, 3, 3, 5] | |
# Selection sort | |
def selection_sort(a) | |
(a.length - 1).times do |outer| | |
minimum = 100000000 | |
minimum_index = -1 | |
outer.upto(a.length - 1) do |inner| | |
if minimum > a[inner] | |
minimum = a[inner] | |
minimum_index = inner | |
end | |
end | |
a[outer], a[minimum_index] = a[minimum_index], a[outer] | |
end | |
return a | |
end | |
# Insertion sort | |
def insertion_sort(a) | |
1.upto(a.length - 1) do |outer| | |
prvek = a[outer] | |
inner = outer - 1 | |
while inner >= 0 && a[inner] > prvek | |
a[inner + 1] = a[inner] | |
inner -= 1 | |
end | |
a[inner + 1] = prvek | |
end | |
return a | |
end | |
# Bubble sort | |
def bubble_sort(a) | |
begin | |
sorted = true | |
for x in (0..(a.length - 2)) | |
if a[x] > a[x + 1] | |
a[x], a[x + 1] = a[x + 1], a[x] | |
sorted = false | |
end | |
end | |
end until sorted | |
return a | |
end | |
# Heap sort | |
def build_heap(a) | |
1.upto(a.length - 1) do |i| | |
up(a, i) | |
end | |
end | |
def up(a, i) | |
son = i | |
while son > 0 | |
father = (son - 1) / 2 | |
if a[father] < a[son] | |
a[father], a[son] = a[son], a[father] | |
son = father | |
else | |
return | |
end | |
end | |
end | |
def heap_sort(a) | |
build_heap(a) | |
index = a.length - 1 | |
while index > 0 | |
a[0], a[index] = a[index], a[0] | |
index -= 1 | |
down(a, index) | |
end | |
end | |
def down(a, index) | |
father = 0 | |
while father * 2 + 1 <= index | |
son = father * 2 + 1 | |
if son < index && a[son] < a[son + 1] | |
son = son + 1 | |
end | |
if a[father] < a[son] | |
a[father], a[son] = a[son], a[father] | |
father = son | |
end | |
end | |
end | |
#nejhur n x m, prumerne n + m | |
def string_search(kupka, jehla) | |
(kupka.length - jehla.length).times do |i| | |
j = 0 | |
while j < jehla.length && kupka[i + j] == jehla[j] | |
j += 1 | |
end | |
if j == jehla.length | |
return i | |
end | |
end | |
return "nenaslo se" | |
end | |
kupka = "nenavidim algoritmy z celeho srdce, ale chci se zlepsit a tak se je naucim a dostanu jednicku " | |
jehla = "jednicku" | |
p string_search(kupka, jehla) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment