Friday, 25 November 2016

Bubble sort revised

Difficulty:
Easy

Instructions:
Implement in place sorting algorithm with a worst case time complexity of O(n2)

Problem and Solution:

class BubbleSort
def self.sort(inA)
n = inA.length
1.upto(n-1) do |k|
swapped = false
0.upto(n-k-1) do |i|
inA[i], inA[i+1] = inA[i+1], inA[i] if inA[i] > inA[i+1]
end
end
inA
end
end
inA = [1, 10,7, 6, 9]
puts BubbleSort.sort(inA)

Bubble Sort

Difficulty:
Easy

Instructions:
Implement in place sorting algorithm with a worst case time complexity of O(n2)

Problem and Solution:

class Bubblesort
def initialize(unsorted_array, order='ASC')
@input_array = unsorted_array
@len = unsorted_array.length
@opr = order == 'ASC' ? '>' : '<'
end
def sort
@len.times do
@input_array.each_with_index do |ele, i|
break if i+2 > @len
@input_array[i], @input_array[i+1] =
@input_array[i+1], ele if ele.to_i.send(@opr, @input_array[i+1].to_i)
end
end
@input_array
end
end
p Bubblesort.new([98,23,54,6,nil,'string',90,0,5,4,1,2], 'ASC').sort
p Bubblesort.new([98,23,54,6,nil,90,0,5,4,1,2], 'DESC').sort
p Bubblesort.new([98,23,54,6,nil,90,0,5,4,1,2]).sort
view raw bubble_sort.rb hosted with ❤ by GitHub

Tuesday, 22 November 2016

Selection Sort

Difficulty:
Easy

Instructions:
Implement in place sorting algorithm with a worst case time complexity of O(n2)

Problem and Solution:

class SelectionSort
def initialize(unsorted_array, order='ASC')
@input_array = unsorted_array
@len = unsorted_array.length
@opr = order == 'ASC' ? '>' : '<'
@current_min_index = 0
end
def sort
@len.times do |i|
index_min = i
(i + 1).upto(@len) do |j|
# Find the minimum value's index
index_min = j if @input_array[j].to_i < @input_array[index_min].to_i
end
@input_array[i], @input_array[index_min] = @input_array[index_min], @input_array[i] if index_min != i
end
@input_array
end
end
p 'Input: [98,23,54,6,nil,90,0,5,4,1,2]'
p SelectionSort.new([98,23,54,6,nil,90,0,5,4,1,2]).sort