Reputation: 91
I have an ArrayList of Integer amd method that calculates its mediana.
public Integer caclucateMediana(){
//some calculations
...
}
I'm trying to implement method SortByMediana and use the recursion, but not sure if it's the correct solution.
public String sortByMediana (){
int mediana = 0;
String result = "";
ArrayList list = new ArrayList<Integer>();
for (Integer number : this) {
list.add(number);
}
result = recMethod(list);
return result;
}
public String recMethod (ArrayList<Integer> list)
{
int mediana = 0;
String result = "";
if (list.size() > 0){
mediana = caclucateMediana();
ArrayList<Integer> newList = (ArrayList<Integer>)list.clone();
newList.remove((Object) mediana);
result += recMethod(newList);
}
return result;
}
Any ideas how to sort ListArray with this method and return String with the result?
Upvotes: 0
Views: 232
Reputation: 88727
As already stated in my comment, a simple loop should do. Since the median is the center element of a collection we can define its zero-based index as collection.size()-1/2
(indices range from 0 to size()-1).
Due to integer math this also takes care of selecting the left element of the center pair in a collection of even length, e.g. in [0, 1, 3, 4]
you want to select 1 which is at index 1. Thus 4-1 = 3
and 3/2 = 1
takes care of this.
Thus building the result could be as simple as:
//copy the original list to keep it untouched
List<Integer> listCopy = new ArrayList<>(list);
StringBuilder sb = new StringBuilder();
while(!listCopy.isEmpty()) {
//append a space if we already have content
if( sb.length() > 0) {
sb.append(" ");
}
//calculate the index (see above)
int medianIndex = listCopy.size() - 1 / 2;
//get the median and remove it from the list
Integer median = listCopy.remove(medianIndex);
//append the median to the string builder
sb.append(median);
}
String result = sb.toString();
Upvotes: 1
Reputation: 12665
Another approach without recursion (assuming that your method calculateMediana
actually takes the List<Integer>
in entry and returns the median Integer
):
public String sortByMediana(List<Integer> list) {
StringBuilder builder = new StringBuilder();
List<Integer> analyzed = new ArrayList<>(list);
while (!analyzed.isEmpty()) {
Integer mediana = calculateMediana(analyzed);
builder.add(mediana).add(" ");
analyzed.remove(analyzed.indexOf(mediana));
}
return builder.toString();
}
Explanation:
analyzed
which is a copy of the input listcalculateMediana
analyzed
Upvotes: 2