Mergesort, I don't understand one line of code
Code:
public class Mergesort {
private static List<Integer> mergesort(List <Integer> unsorted){
if(unsorted.size() <= 1) return unsorted; // Base case: if the size of the list is 1 or nothing then just return that list
//if not...then
int size = unsorted.size();
List<Integer> left = mergesort(unsorted.subList(0, size/2)); //divided the list from 0 ~ half
List<Integer> right = mergesort(unsorted.subList(size/2, size)); // divided the list from half~full
int l = 0;
int r = 0;
ArrayList <Integer> result = new ArrayList<Integer>(); // created new arrayList that will store those values in mergesort list
while((l < left.size()) || r < right.size()){
if(l == left.size() || (r < right.size() [B]&& left.get(l) > right.get(r)[/B] THIS PART)){
result.add(right.get(r));
r++;
}else{
result.add(left.get(l));
l++;
}
}
return result;
}
public static void main(String[] args){
ArrayList <Integer> list = new ArrayList <Integer>();
System.out.println("Please enter numbers (Ctrl+D to terminate)");
Scanner input = new Scanner(System.in);
while(input.hasNextInt()){
list.add(input.nextInt());
}
System.out.println("Unsorted: " + list);
List <Integer> sortedList = mergesort(list);
System.out.println("Sorted: " + sortedList);
}
}
I don't understand the part that I bolded. please explain to me what it does thank you.
Re: Mergesort, I don't understand one line of code
Quote:
Originally Posted by
gomdohri
I don't understand the part that I bolded. please explain to me what it does thank you.
I don't see any boldfaces lines ...
kind regards,
Jos
Re: Mergesort, I don't understand one line of code
Next time mabye it would help if you would take similar long if statement to different parts and try to understand the meaning of each part sepperately.
Code:
if (l == left.size()) // there is nothing to take from left so take from right
// if previous statement is false
if(r < right.size()) // there is something to take from left but is it bigger then the right value. Move to next if to find out.
if(left.get(l) > right.get(r)) // yes the bigger value is on the left side. this means that we take the smaller value from right side and add it to final result << This is what interested you.