diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..b946402 Binary files /dev/null and b/.DS_Store differ diff --git a/lib/.DS_Store b/lib/.DS_Store new file mode 100644 index 0000000..ace602a Binary files /dev/null and b/lib/.DS_Store differ diff --git a/lib/reverse_sentence.rb b/lib/reverse_sentence.rb index 3fe7cac..32dd24b 100644 --- a/lib/reverse_sentence.rb +++ b/lib/reverse_sentence.rb @@ -1,6 +1,22 @@ # A method to reverse the words in a sentence, in place. -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(n) +# Space complexity: O(1) def reverse_sentence(my_sentence) - raise NotImplementedError + + if my_sentence == nil + return nil + elsif + my_sentence == "" + return "" + end + + array = my_sentence.split(/(\S*|\s*)/) # Split by each word and each space + i = 0 + + array.each do |match| + position = -i + my_sentence.length - match.length + + my_sentence[position...position+match.length] = match + i += match.length + end end diff --git a/lib/sort_by_length.rb b/lib/sort_by_length.rb index a5713ad..08a2e60 100644 --- a/lib/sort_by_length.rb +++ b/lib/sort_by_length.rb @@ -1,7 +1,25 @@ # 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" + array = my_sentence.split + length = array.length + i = 0 + + while i < length-1 + j = 0 + while j < length-i-1 + if array[j].length > array[j+1].length # compares the length of each word + temp = array[j] + array[j] = array[j+1] + array[j+1] = temp + end + j += 1 + end + i += 1 + end + + return 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