Problem : Given an array of Strings with alphabetical string values and integer String values, sort the array mentaining their respective order of data type.
For Ex : Input ["bat", "cat", "3", "apple", "1", "2", "11"]
Result : ["apple", "bat", "1", "cat", "2", "3", "11"]
Basic idea is to first sort the string (which might not have natural sorted order for numbers), then create a Treeset of integer and string. Tree set will mention their natural sorting order. Then check the type of each index in original array and insert elements from trees one by one in the array based on index type in original array.
Basic idea is to first sort the string (which might not have natural sorted order for numbers), then create a Treeset of integer and string. Tree set will mention their natural sorting order. Then check the type of each index in original array and insert elements from trees one by one in the array based on index type in original array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | public String[] sortAlphanumeric(String[] input){ if(input== null || input.length == 1){ return input; } String[] temp = Arrays.copyOf(input, input.length); Arrays.sort(temp); Set<Integer> intgr = new TreeSet<Integer>(); Set<String> str = new TreeSet<String>(); for(int i=0; i < temp.length; i++){ try{ int t= Integer.parseInt(temp[i]); intgr.add(t); }catch(NumberFormatException e){ str.add(temp[i]); } } for(int k=0; k< temp.length; k++){ boolean isIntgr = checkType(input[k]); if(isIntgr){ temp[k] = intgr.iterator().next() + ""; intgr.remove(intgr.iterator().next() ); }else{ temp[k] = str.iterator().next(); str.remove(temp[k] ); } } return temp; } public static boolean checkType(String s){ try{ Integer.parseInt(s); return true; }catch(NumberFormatException e){ return false; } } public static void swap(int i, int j, String [] input){ String temp = input[i]; input[i] = input[j]; input[j] = temp; } |
No comments:
Post a Comment