Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 46 additions & 4 deletions lib/reverse_sentence.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,48 @@
# A method to reverse the words in a sentence, in place.
# Time complexity: ?
# Space complexity: ?
def reverse_sentence(my_sentence)
raise NotImplementedError
# Time complexity: O(N)
# Space complexity: O(N)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since you're not making another string or array, this is actually O(1) space complexity.


# reverse string given start and ending index
def reverse_word(string, start, ending)

i = start
j = ending

while i < j
temp = string[i]
string[i] = string[j]
string[j] = temp

i += 1
j -= 1
end
end
Comment on lines +6 to +19

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Love the helper method!


# call method made to reverse sentence

def reverse_sentence(string)
if string == nil
return
end
reverse_word(string, 0, string.length - 1)
start = 0
while start < string.length
if string[start] == " "
start += 1
next

else # found the start of a word
ending = start
while ending <= string.length
if string[ending] == " " || ending == string.length
reverse_word(string, start, ending - 1)
start = ending
break
end

ending += 1

end
end
end
end
26 changes: 23 additions & 3 deletions lib/sort_by_length.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,27 @@
# A method which will return an array of the words in the string
# sorted by the length of the word.
# Time complexity: ?
# Space complexity: ?
# Time complexity: O(N^2)
# Space complexity: O(N)

def sort_by_length(my_sentence)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice Bubblesort!

raise NotImplementedError, "Method not implemented"
sentence_array = my_sentence.split(" ")
bubble_sort(sentence_array, sentence_array.length)
return sentence_array
end

# cite: https://github.com/Ada-Developers-Academy/textbook-curriculum/blob/master/04-cs-fundamentals/classroom/Sorting.md
def bubble_sort(array, length)
i = 0
while i < length - 1 # outer loop
j = 0
while j < length-i-1 # inner loop
if array[j].length > array[j+1].length # swap if length of word is greater than other
temp = array[j]
array[j] = array[j+1]
array[j+1] = temp
end
j += 1
end
i += 1
end
end
File renamed without changes.