|
1 | 1 | # Time complexity:
|
2 | 2 | # Omega(n^2)
|
3 | 3 | # Teta(n^2)
|
4 |
| -# |
5 |
| -values = [5,2,4,7,1,3,6] |
6 |
| -print "Input: " |
7 |
| -p values |
8 |
| - |
9 |
| -# Solve bubble sort using loop |
10 |
| -def l_selection_sort(values) |
11 |
| - len = values.size |
12 |
| - (0...len-1).each do |i| |
13 |
| - min_index = i |
14 |
| - (i...len).each do |j| |
15 |
| - if(values[j] < values[min_index]) |
16 |
| - min_index = j |
| 4 | +# |
| 5 | +class SelectionSort |
| 6 | + class << self |
| 7 | + def recursive(values, i=0) |
| 8 | + len = values.size |
| 9 | + if(i >= len) |
| 10 | + return values |
| 11 | + end |
| 12 | + j = i+1 |
| 13 | + min_index = i |
| 14 | + while(j < len) |
| 15 | + if(values[j] < values[min_index]) |
| 16 | + min_index = j |
| 17 | + end |
| 18 | + j += 1 |
17 | 19 | end
|
| 20 | + values[i], values[min_index] = values[min_index], values[i] |
| 21 | + return recursive(values, i+1) |
18 | 22 | end
|
19 |
| - values[i], values[min_index] = values[min_index], values[i] |
20 |
| - end |
21 |
| - return values |
22 |
| -end |
23 | 23 |
|
24 |
| -print "Result: " |
25 |
| -p l_selection_sort(values) |
26 |
| - |
27 |
| -values = [5,2,4,7,1,3,6] |
28 |
| -def r_selection_sort(values, i) |
29 |
| - len = values.size |
30 |
| - if(i >= len) |
31 |
| - return values |
32 |
| - end |
33 |
| - j = i+1 |
34 |
| - min_index = i |
35 |
| - while(j < len) |
36 |
| - if(values[j] < values[min_index]) |
37 |
| - min_index = j |
| 24 | + # Solve bubble sort using loop |
| 25 | + def non_recursive(values) |
| 26 | + len = values.size |
| 27 | + (0...len-1).each do |i| |
| 28 | + min_index = i |
| 29 | + (i...len).each do |j| |
| 30 | + if(values[j] < values[min_index]) |
| 31 | + min_index = j |
| 32 | + end |
| 33 | + end |
| 34 | + values[i], values[min_index] = values[min_index], values[i] |
| 35 | + end |
| 36 | + return values |
38 | 37 | end
|
39 |
| - j += 1 |
40 | 38 | end
|
41 |
| - values[i], values[min_index] = values[min_index], values[i] |
42 |
| - return r_selection_sort(values, i+1) |
43 | 39 | end
|
44 |
| - |
45 |
| -print "Result: " |
46 |
| -p r_selection_sort(values, 0) |
0 commit comments