The question is to sort an array of Strings, based on the length of the strings.
For example
input = {"cat", "star", "act", "gid", "arts", "dog", "rats"}
output = {"cat", "act", "gid", "dog", "star", "arts", "rats"}
I did it using Insertion sort(using the length of the strings instead of the strings themselves). My question:is there a better way to do it?
An alternative I thought of is - use a TreeMap to store each string and its length as value (assume the strings are unique in the given array). Then sort it based on its values. The running time would be O(nlogn) and space complexity would be O(n). Do you think this is a better approach?
EDIT: Sorry for not mentioning this earlier - I want to do this without using Arrays.sort() or a custom comparator.
Code sample for insertion sort:
public static String[] insertionSort(String[] arr) {
for(int i=1;i<arr.length;i++) {
int j = 0;
for(;j<i;j++) {
if(arr[j].length() > arr[j+1].length()) {
String temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
O(n)for both time and space as there is no need to order elements, just initial pass of bucket sort.HashMapsuggestion.