-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExam5.rb
More file actions
39 lines (36 loc) · 767 Bytes
/
Exam5.rb
File metadata and controls
39 lines (36 loc) · 767 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# frozen_string_literal: true
def max_heap_maker(arr, n, i)
max = i
left = 2 * i + 1
right = 2 * i +2
if (left < n && arr[left] > arr[max])
max = left
end
if (right < n && arr[right] > arr[max])
max = right
end
if (max != i)
swap(arr, i, max)
max_heap_maker(arr, n, max)
end
end
def swap (arr, i, j)
buf = arr[i]
arr[i] = arr[j]
arr[j] = buf
end
def heapsorter(arr)
n = arr.length
for i in (n / 2 - 1).downto(0)
max_heap_maker(arr, n, i)
end
for i in (n - 1).downto(1)
swap(arr, 0, i)
max_heap_maker(arr, i, 0)
end
end
@numbers = []
puts "enter numbers separated with 1 space "
@numbers = gets.split(" ").map(&:to_i)
heapsorter(@numbers)
puts "Result: #{@numbers}"