diff --git a/lib/reverse_sentence.rb b/lib/reverse_sentence.rb index 3fe7cac..1ffad80 100644 --- a/lib/reverse_sentence.rb +++ b/lib/reverse_sentence.rb @@ -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) + +# 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 + +# 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 diff --git a/lib/sort_by_length.rb b/lib/sort_by_length.rb index a5713ad..e7ee463 100644 --- a/lib/sort_by_length.rb +++ b/lib/sort_by_length.rb @@ -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) - 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 diff --git a/test/sort_by_length.rb b/test/sort_by_length_test.rb similarity index 100% rename from test/sort_by_length.rb rename to test/sort_by_length_test.rb