Last active
August 29, 2015 13:57
-
-
Save tony612/9764110 to your computer and use it in GitHub Desktop.
Algrithom
This file contains hidden or 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
| def fibonaci1(n) | |
| return n if n <= 1 | |
| fibonaci1(n - 1) + fibonaci1(n - 2) | |
| end | |
| def fibonaci2(n) | |
| helper = lambda do |a, b, i| | |
| return b if i <= 1 | |
| helper.call(b, a + b, i - 1) | |
| end | |
| helper.call(0, 1, n) | |
| end | |
| p fibonaci1(10) | |
| p fibonaci2(10) |
This file contains hidden or 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
| def quick_sort(arr) | |
| quick_sort_helper(arr, 0, arr.count - 1) | |
| end | |
| def quick_sort_helper(arr, p, r) | |
| if p < r | |
| q, arr = partition(arr, p, r) | |
| quick_sort_helper(arr, p, q - 1) + quick_sort_helper(arr, q + 1, r) | |
| end | |
| arr | |
| end | |
| def partition(arr, p, r) | |
| x = arr[r] | |
| i = p - 1 | |
| (p..r-1).each do |j| | |
| n = arr[j] | |
| if n <= x | |
| i += 1 | |
| arr[i], arr[j] = n, arr[i] | |
| end | |
| end | |
| arr[i + 1], arr[r] = arr[r], arr[i + 1] | |
| [i + 1, arr] | |
| end | |
| arr = [2, 8, 7, 1, 3, 5, 6, 4] | |
| p quick_sort(arr) | |
| # ruby style | |
| def quick_sort2(arr) | |
| return [] if arr == [] | |
| x, *xs = *arr | |
| left, right = xs.partition { |n| n < x } | |
| quick_sort2(left) + [x] + quick_sort2(right) | |
| end | |
| p quick_sort2(arr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment