-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickSort.rb
More file actions
83 lines (68 loc) · 1.37 KB
/
Copy pathquickSort.rb
File metadata and controls
83 lines (68 loc) · 1.37 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# Quick Sort
$c = 0
def quickSort(a,l,r)
return a if r - l <= 0
p = partition(a,l,r)
quickSort(a,l,p-1)
quickSort(a,p+1,r)
a
end
def partition(a,l,r)
#Get middle element and swap
# if l == 0
# # its even
# if (r + 1)%2==0
# m = ((r + 1)/2) - 1
# else
# m = (r+1)/2
# end
# else
# m = (r + l)/2
# end
#
#puts "Array : #{a}"
#puts "l is #{l} , r is #{r}"
#puts "A at m is : #{a[m]}"
#puts "First value is #{a[l]}"
#puts "Last value is #{a[r]}"
#x = a[l]
#b = a[m]
#c = a[r]
#middle = (x <= b) ? ((b <= c) ? b : ((x < c) ? c : x)) : ((x <= c) ? x : ((b < c) ? c : b))
#if middle == a[l]
# m = l
#elsif middle == a[m]
# m = m
#elsif middle == a[r]
# m = r
#end
#puts "#{a[l]} < #{a[m]} < #{a[r]}"
#puts "Middle is #{a[m]}"
#a[l],a[m] = a[m],a[l]
# Always using last element
#Swap first and last
#a[l],a[r] = a[r],a[l]
p = a[l]
i = l + 1
for j in i..r
$c += 1
if a[j] < p #do nothing if it's bigger
a[j], a[i] = a[i], a[j] #swap
i += 1
end
end
a[l],a[i-1], = a[i-1],a[l]
return i-1
end
def qsort(list)
return list if list.size <= 1
pivot = list.shift
left, right = list.partition {|e| e < pivot }
qsort(left) + [pivot] + qsort(right)
end
if __FILE__ == $PROGRAM_NAME
contents = File.open('./QuickSort.txt').read.split("\n")
contents = contents.map {|i| i.to_i}
quickSort(contents,l=0,r=contents.size-1)
puts "Count is : #{$c}"
end