diff --git a/lib/reverse_sentence.rb b/lib/reverse_sentence.rb index 3fe7cac..c08241c 100644 --- a/lib/reverse_sentence.rb +++ b/lib/reverse_sentence.rb @@ -1,6 +1,41 @@ # A method to reverse the words in a sentence, in place. -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(n^2), n == length of my_sentence string +# Space complexity: O(1) def reverse_sentence(my_sentence) - raise NotImplementedError -end + if my_sentence == "" || my_sentence == nil + return my_sentence + end + a = 0 + max_index = my_sentence.length - 1 + b = max_index + while a < b do + temp = my_sentence[a] + my_sentence[a] = my_sentence[b] + my_sentence[b] = temp + a += 1 + b -=1 + end + i = 0 + while i < max_index do + if my_sentence[i] == " " + i += 1 + else + j = i + 1 + while j <= max_index && my_sentence[j] != " " do + j += 1 + end + word_end_index = j + j -= 1 + while i < j do + temp_i = my_sentence[i] + my_sentence[i] = my_sentence[j] + my_sentence[j] = temp_i + i += 1 + j -= 1 + end + i = word_end_index + end + end + return my_sentence +end + diff --git a/lib/sort_by_length.rb b/lib/sort_by_length.rb index a5713ad..044ec82 100644 --- a/lib/sort_by_length.rb +++ b/lib/sort_by_length.rb @@ -1,7 +1,26 @@ # 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), n == number of words in the sentence +# Space complexity: 1 def sort_by_length(my_sentence) - raise NotImplementedError, "Method not implemented" + sentence_array = my_sentence.split + length = sentence_array.length + (0...(length - 1)).each do |i| + min_index = i + j = i + 1 + while j < length + if sentence_array[j].length < sentence_array[min_index].length + min_index = j + end + j += 1 + end + if min_index != i + temp = sentence_array[min_index] + sentence_array[min_index] = sentence_array[i] + sentence_array[i] = temp + end + i += 1 + end + return sentence_array 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