Thread: Mergesort, I don't understand one line of code

1. Member
Join Date
Sep 2011
Posts
22
Rep Power
0

Mergesort, I don't understand one line of code

Java 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)){
r++;
}else{
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()){
}
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.

2. Re: Mergesort, I don't understand one line of code

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

3. Member
Join Date
Dec 2010
Posts
18
Rep Power
0

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.

Java 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.

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•