Results 1 to 3 of 3
- 10-22-2011, 12:35 PM #1
Member
- Join Date
- Sep 2011
- Posts
- 22
- Rep Power
- 0
Mergesort, I don't understand one line of code
I don't understand the part that I bolded. please explain to me what it does thank you.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)){ 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); } }
- 10-22-2011, 02:37 PM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,427
- Blog Entries
- 7
- Rep Power
- 17
- 10-22-2011, 07:37 PM #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.
Similar Threads
-
Can any one help me to understand the Code
By soomroimran in forum New To JavaReplies: 2Last Post: 04-28-2011, 09:23 AM -
Understand Code
By Quizzle23 in forum New To JavaReplies: 9Last Post: 03-07-2011, 10:07 PM -
Constructors pls explan the code line by line in comments
By vibaviattigala in forum New To JavaReplies: 1Last Post: 02-19-2011, 04:03 AM -
understand the code
By prof.deedee in forum New To JavaReplies: 8Last Post: 11-11-2009, 02:43 AM -
Trying to understand this code
By new2java2009 in forum New To JavaReplies: 2Last Post: 09-09-2009, 07:18 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks