<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-6326223989111236657</id><updated>2012-02-07T21:08:28.451-08:00</updated><title type='text'>Java Sorting</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>27</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-5674440002197656706</id><published>2010-01-11T11:07:00.000-08:00</published><updated>2010-01-11T11:08:09.459-08:00</updated><title type='text'>Selection Sort Algorithm in Java</title><content type='html'>The selection sort improves on the bubble sort by reducing the number of swaps necessary from O(N2) to O(N). Unfortunately, the number of comparisons remains O(N2). However, the selection sort can still offer a significant improvement for large records that must be physically moved around in memory, causing the swap time to be much more important than the comparison time. (Typically, this isn’t the case in Java, where references are moved around, not entire objects.)&lt;br /&gt;&lt;div class="style1"&gt;Selection Sort on the Baseball Players&lt;br /&gt;&lt;/div&gt;Let’s consider the baseball players again. In the selection sort, you can no longer compare only players standing next to each other. Thus, you’ll need to remember a certain player’s height; you can use a notebook to write it down. A magenta-colored towel will also come in handy.&lt;br /&gt;&lt;b&gt;A Brief Description&lt;/b&gt;&lt;br /&gt;What’s involved in the selection sort is making a pass through all the players and   picking (or selecting, hence the name of the sort) the shortest one. This shortest   player is then swapped with the player on the left end of the line, at position 0. Now   the leftmost player is sorted and won’t need to be moved again. Notice that in this   algorithm the sorted players accumulate on the left (lower indices), whereas in the bubble sort they accumulated on the right.&lt;br /&gt;The next time you pass down the row of players, you start at position 1, and, finding   the minimum, swap with position 1. This process continues until all the players are   sorted.&lt;br /&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;&lt;b&gt;A More Detailed Description&lt;/b&gt;&lt;br /&gt;In more detail, start at the left end of the line of players. Record the leftmost player’s   height in your notebook and throw the magenta towel on the ground in front of   this person. Then compare the height of the next player to the right with the height   in your notebook. If this player is shorter, cross out the height of the first player and   record the second player’s height instead. Also move the towel, placing it in front of   this new “shortest” (for the time being) player. Continue down the row, comparing   each player with the minimum. Change the minimum value in your notebook and   move the towel whenever you find a shorter player. When you’re done, the magenta towel will be in front of the shortest player.&lt;br /&gt;Swap this shortest player with the player on the left end of the line. You’ve now sorted one player. You’ve made N-1 comparisons, but only one swap.&lt;br /&gt;On the next pass, you do exactly the same thing, except that you can completely   ignore the player on the left because this player has already been sorted. Thus, the   algorithm starts the second pass at position 1, instead of 0. With each succeeding   pass, one more player is sorted and placed on the left, and one less player needs to   be considered when finding the new minimum.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="style1"&gt;Java Code for Selection Sort &lt;br /&gt;&lt;/div&gt;The listing for the selectSort.java program is similar to that for bubbleSort.java, except that the container class is called ArraySel instead of ArrayBub, and the bubbleSort() method has been replaced by selectSort(). Here’s how this method looks:&lt;br /&gt;&lt;div class="style3"&gt;public void selectionSort()&lt;br /&gt;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;int out, in, min;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;for(out=0; out&lt;nelems-1; out++)=""&gt;// outer loop&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;min = out; // minimum&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;for(in=out+1; in&lt;nelems; in++)=""&gt;// inner loop&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;if(a[in] &amp;lt; a[min] ) // if min greater,&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;min = in; // we have a new min&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;swap(out, min); // swap them&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;} // end for(out)&lt;br /&gt;} // end selectionSort()&lt;/nelems;&gt;&lt;/nelems-1;&gt;&lt;br /&gt;&lt;/div&gt;The outer loop, with loop variable out, starts at the beginning of the array (index 0)   and proceeds toward higher indices. The inner loop, with loop variable in, begins at out and likewise proceeds to the right.&lt;br /&gt;At each new position of in, the elements a[in] and a[min] are compared. If a[in] is smaller, then min is given the value of in. At the end of the inner loop, min points to the minimum value, and the array elements pointed to by out and min are swapped.&lt;br /&gt;&lt;div class="style3"&gt;// selectSort.java&lt;br /&gt;// demonstrates selection sort&lt;br /&gt;////////////////////////////////////////////////////////////////&lt;br /&gt;class ArraySel&lt;br /&gt;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; private long[] a; // ref to array a&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; private int nElems; // number of data items&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; //--------------------------------------------------------------&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public ArraySel(int max) // constructor&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;a = new long[max]; // create the array&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;nElems = 0; // no items yet&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; //--------------------------------------------------------------&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public void insert(long value) // put element into array&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;a[nElems] = value; // insert it&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;nElems++; // increment size&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; //--------------------------------------------------------------&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public void display() // displays array contents&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;for(int j=0; j&lt;nelems; j++)=""&gt;// for each element,&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;System.out.print(a[j] + “ “); // display it&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;System.out.println(“”);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; //--------------------------------------------------------------&lt;br /&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;public void selectionSort()&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; int out, in, min;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; for(out=0; out&lt;nelems-1; out++)=""&gt;// outer loop&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;min = out; // minimum&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;for(in=out+1; in&lt;nelems; in++)=""&gt;// inner loop&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;if(a[in] &amp;lt; a[min] ) // if min greater,&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;min = in; // we have a new min&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;swap(out, min); // swap them&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; } // end for(out)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } // end selectionSort()&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; //--------------------------------------------------------------&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; private void swap(int one, int two)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;long temp = a[one];&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;a[one] = a[two];&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;a[two] = temp;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; //--------------------------------------------------------------&lt;br /&gt;} // end class ArraySel&lt;br /&gt;////////////////////////////////////////////////////////////////&lt;br /&gt;class SelectSortApp&lt;br /&gt;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;public static void main(String[] args)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;int maxSize = 100; // array size&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;ArraySel arr; // reference to array&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;arr = new ArraySel(maxSize); // create the array&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;arr.insert(77); // insert 10 items&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;arr.insert(99);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;arr.insert(44);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;arr.insert(55);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;arr.insert(22);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;arr.insert(88);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;arr.insert(11);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;arr.insert(00);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;arr.insert(66);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;arr.insert(33);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;arr.display(); // display items&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;arr.selectionSort(); // selection-sort them&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;arr.display(); // display them again&lt;br /&gt;&amp;nbsp;&amp;nbsp; } // end main()&lt;br /&gt;} // end class SelectSortApp&lt;br /&gt;////////////////////////////////////////////////////////////////&lt;/nelems;&gt;&lt;/nelems-1;&gt;&lt;/nelems;&gt;&lt;br /&gt;&lt;/div&gt;The output from selectSort.java is identical to that from bubbleSort.java:&lt;br /&gt;&lt;div class="style3"&gt;77 99 44 55 22 88 11 0 66 33&lt;br /&gt;0 11 22 33 44 55 66 77 88 99&lt;br /&gt;&lt;/div&gt;Invariant&lt;br /&gt;In the selectSort.java program, the data items with indices less than or equal to out are always sorted.&lt;br /&gt;Efficiency of the Selection Sort&lt;br /&gt;The selection sort performs the same number of comparisons as the bubble sort:   N*(N-1)/2. For 10 data items, this is 45 comparisons. However, 10 items require fewer   than 10 swaps. With 100 items, 4,950 comparisons are required, but fewer than 100   swaps. For large values of N, the comparison times will dominate, so we would have   to say that the selection sort runs in O(N2) time, just as the bubble sort did. However,   it is unquestionably faster because there are so few swaps. For smaller values of N,   the selection sort may in fact be considerably faster, especially if the swap times are&lt;br /&gt;much larger than the comparison times.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-5674440002197656706?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/5674440002197656706/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2010/01/selection-sort-algorithm-in-java.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/5674440002197656706'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/5674440002197656706'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2010/01/selection-sort-algorithm-in-java.html' title='Selection Sort Algorithm in Java'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-1568583953732292611</id><published>2009-12-15T23:39:00.001-08:00</published><updated>2009-12-15T23:39:55.041-08:00</updated><title type='text'>Recursion</title><content type='html'>&lt;span style="font-family: Arial; font-size: small;"&gt;&lt;span style="font-size: 13px;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000044;"&gt;&lt;/span&gt;&lt;br /&gt;Simply put, recursion is when a function calls itself. That is, in the course of the function definition there is a call to that very same function. At first this may seem like a never ending loop, or like a dog chasing its tail. It can never catch it. So too it seems our method will never finish. This might be true is some cases, but in practise we can check to see if a certain condition is true and in that case exit (return from) our method. The case in which we end our recursion is called a&amp;nbsp;&lt;b&gt;base case&amp;nbsp;&lt;/b&gt;. Additionally, just as in a loop, we must change some value and incremently advance closer to our base case.&lt;br /&gt;Consider this function.&lt;br /&gt;&lt;tt&gt;void myMethod( int counter)&lt;br /&gt;{&lt;br /&gt;if(counter == 0)&lt;br /&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;return;&lt;br /&gt;else&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;{&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;System.out.println(""+counter);&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;myMethod(--counter);&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;return;&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;}&lt;br /&gt;}&lt;/tt&gt;&lt;br /&gt;This recursion is not infinite, assuming the method is passed a positive integer value. What will the output be?&lt;br /&gt;Consider this method:&lt;br /&gt;&lt;tt&gt;void myMethod( int counter)&lt;br /&gt;{&lt;br /&gt;if(counter == 0)&lt;br /&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;return;&lt;br /&gt;else&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;{&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;System.out.println("hello" + counter);&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;myMethod(--counter);&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;System.out.println(""+counter);&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;return;&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;}&lt;br /&gt;}&amp;nbsp;&lt;/tt&gt;&lt;br /&gt;&lt;span style="font-family: monospace;"&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: monospace;"&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;If the method is called with the value 4, what will the output be? Explain.&lt;br /&gt;The above recursion is essentially a loop like a for loop or a while loop. When do we prefer recursion to an iterative loop? We use recursion when we can see that our problem can be reduced to a simpler problem that can be solved after further reduction.&lt;br /&gt;Every recursion should have the following characteristics.&lt;br /&gt;&lt;ol&gt;&lt;li&gt;A simple base case which we have a solution for and a return value.&lt;/li&gt;&lt;li&gt;A way of getting our problem closer to the base case. I.e. a way to chop out part of the problem to get a somewhat simpler problem.&lt;/li&gt;&lt;li&gt;A recursive call which passes the simpler problem back into the method.&lt;/li&gt;&lt;/ol&gt;The key to thinking recursively is to see the solution to the problem as a smaller version of the same problem. The key to solving recursive programming requirements is to imagine that your method does what its name says it does even before you have actually finish writing it. You must pretend the method does its job and then use it to solve the more complex cases. Here is how.&lt;br /&gt;Identify the base case(s) and what the base case(s) do. A base case is the simplest possible problem (or case) your method could be passed. Return the correct value for the base case. Your recursive method will then be comprised of an if-else statement where the base case returns one value and the non-base case(s) recursively call(s) the same method with a&amp;nbsp;&lt;b&gt;smaller&lt;/b&gt;&amp;nbsp;parameter or set of data. Thus you decompose your problem into two parts: (1) The simplest possible case which you can answer (and return for), and (2) all other more complex cases which you will solve by returning the result of a second calling of your method. This second calling of your method ( recursion ) will pass on the complex problem but reduced by one increment. This decomposition of the problem will actually be a complete, accurate solution for the problem for all cases other than the base case. Thus, the code of the method actually has the solution on the first recursion.&lt;br /&gt;Let's consider writing a method to find the factorial of an integer. For example 7! equals 7*6*5*4*3*2*1 .&lt;br /&gt;But we are also correct if we say 7! equals 7*6!.&lt;br /&gt;In seeing the factorial of 7 in this second way we have gained a valuable insight. We now can see our problem in terms of a simpler version of our problem and we even know how to make our problem progressively more simple. We have also defined our problem in terms of itself. I.e. we defined 7! in terms of 6!. This is the essence of recursive problem solving. Now all we have left to do is decide what the base case is. What is the simplest factorial? 1!. 1! equals 1.&lt;br /&gt;Let's write the factorial function recursively.&lt;br /&gt;&lt;tt&gt;int myFactorial( int integer)&lt;br /&gt;{&lt;br /&gt;if( integer == 1)&lt;br /&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;return 1;&lt;br /&gt;else&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;{&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;return(integer*(myFactorial(integer-1);&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;}&lt;br /&gt;}&lt;/tt&gt;&lt;br /&gt;Note that the base case ( the factorial of 1 ) is solved and the return value is given. Now let us imagine that our method actually works. If it works we can use it to give the result of more complex cases. If our number is 7 we will simply return 7 * the result of factorial of 6. So we actaully have the exact answer for all cases in the top level recursion. Our problem is getting smaller on each recursive call because each time we call the method we give it a smaller number. Try running this program in your head with the number 2. Does it give the right value? If it works for 1 then it must work for two since 2 merely returns 2 * factorial of 1. Now will it work for 3? Well, 3 must return 3 * factorial of 2. Now since we know that factorial of 2 works, factorial of 3 also works. We can prove that 4 works in the same way, and so on and so on.&lt;br /&gt;Food for thought: ask yourself, could this be written iteratively?&lt;br /&gt;Note: make it your habit of writing the base case in the method as the first statement.&lt;br /&gt;Note: Forgetting the base case leads to infinite recursion.&lt;br /&gt;However, in fact, your code won't run forever like an infinite loop, instead, you will eventually run out of stack space (memory) and get a run-time error or exception called a stack overflow. There are several significant problems with recursion. Mostly it is hard (especially for inexperienced programmers) to think recursively, though many AI specialists claim that in reality recursion is closer to basic human thought processes than other programming methods (such as iteration). There also exists the problem of stack overflow when using some forms of recursion (head recursion.) The other main problem with recursion is that it can be slower to run than simple iteration. Then why use it? It seems that there is always an iterative solution to any problem that can be solved recursively. Is there a difference in computational complexity? No.&lt;br /&gt;Is there a difference in the efficiency of execution? Yes, in fact, the recursive version is usually less efficient because of having to push and and pop recursions on and off the run-time stack, so iteration is quicker. On the other hand, you might notice that the recursive versions use fewer or no local variables.&lt;br /&gt;So why use recursion? The answer to our question is predominantly because it is easier to code a recursive solution once one is able to identify that solution. The recursive code is usually smaller, more concise, more elegant, possibly even easier to understand, though that depends on ones thinking style. But also, there are some problems that are very difficult to solve without recursion. Those problems that require backtracking such as searching a maze for a path to an exit or tree based operations (which we will see in semester 2) are best solved recursively. There are also some interesting sorting algorithms that use recursion.&lt;br /&gt;&lt;h3&gt;&lt;a href="http://www.blogger.com/post-edit.g?blogID=6326223989111236657&amp;amp;postID=1568583953732292611" name="hanoi"&gt;Towers of Hanoi&lt;/a&gt;&lt;/h3&gt;This problem comes from history, monks in Vietnam were asked to carry 64 gold disks from one tower (stack) to another. Each disk is of a different size. There are 3 stacks, a source stack, a destination stack and an intermediate stack. A disk is placed on one of three stacks but&amp;nbsp;&lt;b&gt;no disk can be placed on top of a smaller disk&lt;/b&gt;. The source tower holds 64 disks. How will the monks solve this problem? How long will it take them?&lt;br /&gt;The easiest solution is a recursive one. The key to the solution is to notice that to move any disk, we must first move the smaller disks off of it, thus a recursive definition. Another way to look at it is this, if we had a method to move the top three disks to the middle position, we could put the biggest disk in its place. All we need to do is assume we have this method and then call it.&lt;br /&gt;Lets start with 1 disk (our base case): Move 1 disk from start tower to destination tower and we are done.&lt;br /&gt;To move 2 disks:&lt;br /&gt;Move smaller disk from start tower to intermediate tower, move larger disk from start tower to final tower, move smaller disk from intermediate tower to final tower and we are done.&lt;br /&gt;To move n disks (or think of, say, 3 disks):&lt;br /&gt;Solve the problem for n - 1 disks (i.e. 2 disks) using the intermediate tower instead of the final tower (i.e. get 2 disks onto the intermediate tower). Then , move the biggest disk from start tower to final tower. Then again solve the problem for n - 1 disks but use the intermediate tower instead of the start tower (i.e. get the 2 disks onto the final tower using the start tower as the intermediate tower).&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Tail Recursion&lt;/h3&gt;Tail recursion is defined as occuring when the recursive call is at the end of the recursive instruction. This is not the case with my factorial solution above. It is useful to notice when ones algorithm uses tail recursion because in such a case, the algorithm can usually be rewritten to use iteration instead. In fact, the compiler will (or at least should) convert the recursive program into an iterative one. This eliminates the potential problem of stack overflow.&lt;br /&gt;This is not the case with head recursion, or when the function calls itself recursively in different places like in the Towers of Hanoi solution. Of course, even in these cases we could also remove recursion by using our own stack and essentially simulating how recursion would work.&lt;br /&gt;In my example of factorial above the compiler will have to call the recursive function before doing the multiplication because it has to resolve the (return) value of the function before it can complete the multiplication. So the order of execution will be "head" recursion, i.e. recursion occurs before other operations.&lt;br /&gt;To convert this to tail recursion we need to get all the multiplication finished and resolved before recursively calling the function. We need to force the order of operation so that we are not waiting on multiplication before returning. If we do this the stack frame can be freed up.&lt;br /&gt;The proper way to do a tail-recursive factorial is this:&lt;br /&gt;&lt;pre&gt;int factorial(int number) {&lt;br /&gt;    if(number == 0) {&lt;br /&gt;           return 1;&lt;br /&gt;        }&lt;br /&gt;        factorial_i(number, 1);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int factorial_i(int currentNumber, int sum) {&lt;br /&gt;    if(currentNumber == 1) {&lt;br /&gt;        return sum;&lt;br /&gt;    } else {&lt;br /&gt;        return factorial_i(currentNumber - 1, sum*currentNumber);&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Notice that in the call return&amp;nbsp;factorial_i(currentNumber&amp;nbsp;-&amp;nbsp;1,&amp;nbsp;sum*currentNumber); both parameters are immediately resolvable. We can compute what each parameter is without waiting for a recursive function call to return. This is not the case with the previous version of factorial. This streamlining enables the compiler to minimize stack use as explained above.&amp;nbsp;&lt;i&gt;Thanks to Jon Bartlett for the example.&lt;/i&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-1568583953732292611?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/1568583953732292611/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/12/recursion.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/1568583953732292611'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/1568583953732292611'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/12/recursion.html' title='Recursion'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-3868131917545386167</id><published>2009-12-15T23:38:00.000-08:00</published><updated>2009-12-15T23:38:02.280-08:00</updated><title type='text'>Merge Sort Implementation in Java</title><content type='html'>&lt;span class="Apple-style-span" style="-webkit-border-horizontal-spacing: 2px; -webkit-border-vertical-spacing: 2px; color: #333333; font-family: 'Trebuchet MS', Verdana, Arial, Helvetica, sans-serif; font-size: 11px;"&gt;&lt;/span&gt;&lt;br /&gt;&lt;div style="color: #333333; font-family: 'Trebuchet MS', Verdana, Arial, Helvetica, sans-serif; font-size: 11px;"&gt;In computer science, merge sort or mergesort is a sorting algorithm for rearranging lists (or any other data structure that can only be accessed sequentially, e.g. file streams) into a specified order. It is a particularly good example of the divide and conquer algorithmic paradigm. It is a comparison sort.&lt;br /&gt;&lt;/div&gt;&lt;div style="color: #333333; font-family: 'Trebuchet MS', Verdana, Arial, Helvetica, sans-serif; font-size: 11px;"&gt;Conceptually, merge sort works as follows:&lt;br /&gt;&lt;/div&gt;&lt;ol&gt;&lt;li style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px;"&gt;Divide the unsorted list into two sublists of about half the size&lt;/li&gt;&lt;li style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px;"&gt;Sort each of the two sublists&lt;/li&gt;&lt;li style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px;"&gt;Merge the two sorted sublists back into one sorted list.&lt;/li&gt;&lt;/ol&gt;&lt;div style="color: #333333; font-family: 'Trebuchet MS', Verdana, Arial, Helvetica, sans-serif; font-size: 11px;"&gt;The algorithm was invented by John von Neumann in 1945.&lt;br /&gt;&lt;/div&gt;&lt;div style="color: #333333; font-family: 'Trebuchet MS', Verdana, Arial, Helvetica, sans-serif; font-size: 11px;"&gt;The following code shows how to implement merge sort in Java.&lt;br /&gt;&lt;/div&gt;&lt;div align="left" class="java" style="color: #333333; font-family: 'Trebuchet MS', Verdana, Arial, Helvetica, sans-serif; font-size: 11px;"&gt;&lt;table bgcolor="#ffffff" border="0" cellpadding="3" cellspacing="0"&gt;&lt;tbody&gt;&lt;tr style="color: #333333; font-family: 'Trebuchet MS', Verdana, Arial, Helvetica, sans-serif; font-size: 11px;"&gt;&lt;td align="left" nowrap="nowrap" style="color: #333333; font-family: 'Trebuchet MS', Verdana, Arial, Helvetica, sans-serif; font-size: 11px;" valign="top"&gt;&lt;code&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;/**&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;*&amp;nbsp;Mergesort&amp;nbsp;algorithm.&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;*&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f9fbf;"&gt;@param&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;a&amp;nbsp;an&amp;nbsp;array&amp;nbsp;of&amp;nbsp;Comparable&amp;nbsp;items.&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;*/&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;public&amp;nbsp;static&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;void&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;span style="color: black;"&gt;mergeSort&lt;/span&gt;&lt;span style="color: black;"&gt;(&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;Comparable&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;[&amp;nbsp;]&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;a&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;)&amp;nbsp;{&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;Comparable&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;[&amp;nbsp;]&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;tmpArray&amp;nbsp;=&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;new&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;span style="color: black;"&gt;Comparable&lt;/span&gt;&lt;span style="color: black;"&gt;[&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;a.length&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;]&lt;/span&gt;&lt;span style="color: black;"&gt;;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;mergeSort&lt;/span&gt;&lt;span style="color: black;"&gt;(&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;a,&amp;nbsp;tmpArray,&amp;nbsp;&lt;/span&gt;&lt;span style="color: #990000;"&gt;0&lt;/span&gt;&lt;span style="color: black;"&gt;,&amp;nbsp;a.length&amp;nbsp;-&amp;nbsp;&lt;/span&gt;&lt;span style="color: #990000;"&gt;1&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;)&lt;/span&gt;&lt;span style="color: black;"&gt;;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;}&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;/**&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;*&amp;nbsp;Internal&amp;nbsp;method&amp;nbsp;that&amp;nbsp;makes&amp;nbsp;recursive&amp;nbsp;calls.&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;*&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f9fbf;"&gt;@param&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;a&amp;nbsp;an&amp;nbsp;array&amp;nbsp;of&amp;nbsp;Comparable&amp;nbsp;items.&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;*&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f9fbf;"&gt;@param&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;tmpArray&amp;nbsp;an&amp;nbsp;array&amp;nbsp;to&amp;nbsp;place&amp;nbsp;the&amp;nbsp;merged&amp;nbsp;result.&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;*&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f9fbf;"&gt;@param&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;left&amp;nbsp;the&amp;nbsp;left-most&amp;nbsp;index&amp;nbsp;of&amp;nbsp;the&amp;nbsp;subarray.&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;*&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f9fbf;"&gt;@param&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;right&amp;nbsp;the&amp;nbsp;right-most&amp;nbsp;index&amp;nbsp;of&amp;nbsp;the&amp;nbsp;subarray.&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;*/&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;private&amp;nbsp;static&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;void&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;span style="color: black;"&gt;mergeSort&lt;/span&gt;&lt;span style="color: black;"&gt;(&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;Comparable&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;[&amp;nbsp;]&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;a,&amp;nbsp;Comparable&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;[&amp;nbsp;]&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;tmpArray,&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;int&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;span style="color: black;"&gt;left,&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;int&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;span style="color: black;"&gt;right&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;)&amp;nbsp;{&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;if&lt;/b&gt;&lt;/span&gt;&lt;span style="color: black;"&gt;(&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;left&amp;nbsp;&amp;lt;&amp;nbsp;right&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;)&amp;nbsp;{&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;int&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;span style="color: black;"&gt;center&amp;nbsp;=&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;(&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;left&amp;nbsp;+&amp;nbsp;right&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;)&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;/&amp;nbsp;&lt;/span&gt;&lt;span style="color: #990000;"&gt;2&lt;/span&gt;&lt;span style="color: black;"&gt;;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;mergeSort&lt;/span&gt;&lt;span style="color: black;"&gt;(&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;a,&amp;nbsp;tmpArray,&amp;nbsp;left,&amp;nbsp;center&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;)&lt;/span&gt;&lt;span style="color: black;"&gt;;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;mergeSort&lt;/span&gt;&lt;span style="color: black;"&gt;(&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;a,&amp;nbsp;tmpArray,&amp;nbsp;center&amp;nbsp;+&amp;nbsp;&lt;/span&gt;&lt;span style="color: #990000;"&gt;1&lt;/span&gt;&lt;span style="color: black;"&gt;,&amp;nbsp;right&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;)&lt;/span&gt;&lt;span style="color: black;"&gt;;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;merge&lt;/span&gt;&lt;span style="color: black;"&gt;(&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;a,&amp;nbsp;tmpArray,&amp;nbsp;left,&amp;nbsp;center&amp;nbsp;+&amp;nbsp;&lt;/span&gt;&lt;span style="color: #990000;"&gt;1&lt;/span&gt;&lt;span style="color: black;"&gt;,&amp;nbsp;right&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;)&lt;/span&gt;&lt;span style="color: black;"&gt;;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;}&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;}&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;/**&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;*&amp;nbsp;Internal&amp;nbsp;method&amp;nbsp;that&amp;nbsp;merges&amp;nbsp;two&amp;nbsp;sorted&amp;nbsp;halves&amp;nbsp;of&amp;nbsp;a&amp;nbsp;subarray.&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;*&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f9fbf;"&gt;@param&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;a&amp;nbsp;an&amp;nbsp;array&amp;nbsp;of&amp;nbsp;Comparable&amp;nbsp;items.&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;*&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f9fbf;"&gt;@param&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;tmpArray&amp;nbsp;an&amp;nbsp;array&amp;nbsp;to&amp;nbsp;place&amp;nbsp;the&amp;nbsp;merged&amp;nbsp;result.&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;*&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f9fbf;"&gt;@param&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;leftPos&amp;nbsp;the&amp;nbsp;left-most&amp;nbsp;index&amp;nbsp;of&amp;nbsp;the&amp;nbsp;subarray.&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;*&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f9fbf;"&gt;@param&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;rightPos&amp;nbsp;the&amp;nbsp;index&amp;nbsp;of&amp;nbsp;the&amp;nbsp;start&amp;nbsp;of&amp;nbsp;the&amp;nbsp;second&amp;nbsp;half.&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;*&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f9fbf;"&gt;@param&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;rightEnd&amp;nbsp;the&amp;nbsp;right-most&amp;nbsp;index&amp;nbsp;of&amp;nbsp;the&amp;nbsp;subarray.&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f5fbf;"&gt;*/&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;private&amp;nbsp;static&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;void&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;span style="color: black;"&gt;merge&lt;/span&gt;&lt;span style="color: black;"&gt;(&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;Comparable&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;[&amp;nbsp;]&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;a,&amp;nbsp;Comparable&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;[&amp;nbsp;]&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;tmpArray,&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;int&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;span style="color: black;"&gt;leftPos,&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;int&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;span style="color: black;"&gt;rightPos,&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;int&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;span style="color: black;"&gt;rightEnd&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;)&amp;nbsp;{&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;int&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;span style="color: black;"&gt;leftEnd&amp;nbsp;=&amp;nbsp;rightPos&amp;nbsp;-&amp;nbsp;&lt;/span&gt;&lt;span style="color: #990000;"&gt;1&lt;/span&gt;&lt;span style="color: black;"&gt;;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;int&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;span style="color: black;"&gt;tmpPos&amp;nbsp;=&amp;nbsp;leftPos;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;int&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;span style="color: black;"&gt;numElements&amp;nbsp;=&amp;nbsp;rightEnd&amp;nbsp;-&amp;nbsp;leftPos&amp;nbsp;+&amp;nbsp;&lt;/span&gt;&lt;span style="color: #990000;"&gt;1&lt;/span&gt;&lt;span style="color: black;"&gt;;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f7f5f;"&gt;//&amp;nbsp;Main&amp;nbsp;loop&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;while&lt;/b&gt;&lt;/span&gt;&lt;span style="color: black;"&gt;(&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;leftPos&amp;nbsp;&amp;lt;=&amp;nbsp;leftEnd&amp;nbsp;&amp;amp;&amp;amp;&amp;nbsp;rightPos&amp;nbsp;&amp;lt;=&amp;nbsp;rightEnd&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;)&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;if&lt;/b&gt;&lt;/span&gt;&lt;span style="color: black;"&gt;(&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;a&lt;/span&gt;&lt;span style="color: black;"&gt;[&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;leftPos&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;]&lt;/span&gt;&lt;span style="color: black;"&gt;.compareTo&lt;/span&gt;&lt;span style="color: black;"&gt;(&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;a&lt;/span&gt;&lt;span style="color: black;"&gt;[&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;rightPos&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;]&amp;nbsp;)&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;&amp;lt;=&amp;nbsp;&lt;/span&gt;&lt;span style="color: #990000;"&gt;0&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;)&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;tmpArray&lt;/span&gt;&lt;span style="color: black;"&gt;[&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;tmpPos++&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;]&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;=&amp;nbsp;a&lt;/span&gt;&lt;span style="color: black;"&gt;[&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;leftPos++&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;]&lt;/span&gt;&lt;span style="color: black;"&gt;;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;else&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;tmpArray&lt;/span&gt;&lt;span style="color: black;"&gt;[&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;tmpPos++&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;]&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;=&amp;nbsp;a&lt;/span&gt;&lt;span style="color: black;"&gt;[&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;rightPos++&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;]&lt;/span&gt;&lt;span style="color: black;"&gt;;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;while&lt;/b&gt;&lt;/span&gt;&lt;span style="color: black;"&gt;(&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;leftPos&amp;nbsp;&amp;lt;=&amp;nbsp;leftEnd&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;)&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f7f5f;"&gt;//&amp;nbsp;Copy&amp;nbsp;rest&amp;nbsp;of&amp;nbsp;first&amp;nbsp;half&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;tmpArray&lt;/span&gt;&lt;span style="color: black;"&gt;[&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;tmpPos++&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;]&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;=&amp;nbsp;a&lt;/span&gt;&lt;span style="color: black;"&gt;[&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;leftPos++&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;]&lt;/span&gt;&lt;span style="color: black;"&gt;;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;while&lt;/b&gt;&lt;/span&gt;&lt;span style="color: black;"&gt;(&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;rightPos&amp;nbsp;&amp;lt;=&amp;nbsp;rightEnd&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;)&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f7f5f;"&gt;//&amp;nbsp;Copy&amp;nbsp;rest&amp;nbsp;of&amp;nbsp;right&amp;nbsp;half&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;tmpArray&lt;/span&gt;&lt;span style="color: black;"&gt;[&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;tmpPos++&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;]&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;=&amp;nbsp;a&lt;/span&gt;&lt;span style="color: black;"&gt;[&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;rightPos++&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;]&lt;/span&gt;&lt;span style="color: black;"&gt;;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #3f7f5f;"&gt;//&amp;nbsp;Copy&amp;nbsp;tmpArray&amp;nbsp;back&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;for&lt;/b&gt;&lt;/span&gt;&lt;span style="color: black;"&gt;(&amp;nbsp;&lt;/span&gt;&lt;span style="color: #7f0055;"&gt;&lt;b&gt;int&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;span style="color: black;"&gt;i&amp;nbsp;=&amp;nbsp;&lt;/span&gt;&lt;span style="color: #990000;"&gt;0&lt;/span&gt;&lt;span style="color: black;"&gt;;&amp;nbsp;i&amp;nbsp;&amp;lt;&amp;nbsp;numElements;&amp;nbsp;i++,&amp;nbsp;rightEnd--&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;)&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;a&lt;/span&gt;&lt;span style="color: black;"&gt;[&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;rightEnd&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;]&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;=&amp;nbsp;tmpArray&lt;/span&gt;&lt;span style="color: black;"&gt;[&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;rightEnd&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;]&lt;/span&gt;&lt;span style="color: black;"&gt;;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: white;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="color: black;"&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-3868131917545386167?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/3868131917545386167/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/12/merge-sort-implementation-in-java.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/3868131917545386167'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/3868131917545386167'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/12/merge-sort-implementation-in-java.html' title='Merge Sort Implementation in Java'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-5463508665049885548</id><published>2009-12-12T07:06:00.000-08:00</published><updated>2009-12-12T07:09:53.964-08:00</updated><title type='text'>Binary search</title><content type='html'>&lt;span class="Apple-style-span"   style="color: rgb(51, 51, 51);   line-height: 16px; font-family:Arial, Helvetica, Verdana, sans-serif;font-size:12px;"&gt;&lt;p&gt;&lt;span class="Apple-style-span" style="font-size: medium;"&gt;Binary search is one of the fundamental algorithms in computer science. In order to explore it, we'll first build up a theoretical backbone, then use that to implement the algorithm properly and avoid those nasty off-by-one errors everyone's been talking about.&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;&lt;span class="bodySubtitle" style=" font-weight: bold; "&gt;&lt;span class="Apple-style-span" style="font-size: medium;"&gt;Finding a value in a sorted sequence&lt;/span&gt;&lt;/span&gt;&lt;span class="Apple-style-span" style="font-size: medium;"&gt;&lt;br /&gt;In its simplest form, binary search is used to quickly find a value in a sorted sequence (consider a sequence an ordinary array for now). We'll call the sought value the &lt;/span&gt;&lt;i&gt;&lt;span class="Apple-style-span" style="font-size: medium;"&gt;target&lt;/span&gt;&lt;/i&gt;&lt;span class="Apple-style-span" style="font-size: medium;"&gt; value for clarity. Binary search maintains a contiguous subsequence of the starting sequence where the target value is surely located. This is called the &lt;/span&gt;&lt;i&gt;&lt;span class="Apple-style-span" style="font-size: medium;"&gt;search space&lt;/span&gt;&lt;/i&gt;&lt;span class="Apple-style-span" style="font-size: medium;"&gt;. The search space is initially the entire sequence. At each step, the algorithm compares the median value in the search space to the target value. Based on the comparison and because the sequence is sorted, it can then eliminate half of the search space. By doing this repeatedly, it will eventually be left with a search space consisting of a single element, the target value. &lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span class="Apple-style-span"  style="color: rgb(34, 34, 34);  font-family:'Helvetica Neue', Helvetica, Arial, sans-serif;"&gt;&lt;span class="Apple-style-span" style="font-size: medium;"&gt;TDQVEUZ2BQDE&lt;/span&gt;&lt;/span&gt;&lt;span class="Apple-style-span" style="font-size: medium;"&gt;&lt;br /&gt;&lt;span class="Apple-style-span"  style="font-family:'Courier New';"&gt;&lt;span class="Apple-style-span" style="line-height: 14px; white-space: pre;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-5463508665049885548?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/5463508665049885548/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/12/binary-search.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/5463508665049885548'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/5463508665049885548'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/12/binary-search.html' title='Binary search'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-4496048897337051889</id><published>2009-12-07T04:41:00.000-08:00</published><updated>2009-12-13T04:48:24.391-08:00</updated><title type='text'>Binary Trees</title><content type='html'>&lt;h2&gt;Java Binary Trees and Solutions&lt;/h2&gt;In Java, the key points in the recursion are exactly the same as in C or C++. In fact, I created the Java solutions by just copying the C solutions, and then making the syntactic changes. The recursion is the same, however the outer structure is slightly different. &lt;br /&gt;In Java, we will have a BinaryTree object that contains a single root pointer. The root pointer points to an internal Node class that behaves just like the node struct in the C/C++ version. The Node class is private -- it is used only for internal storage inside the BinaryTree and is not exposed to clients. With this OOP structure, almost every operation has two methods: a one-line method on the BinaryTree that starts the computation, and a recursive method that works on the Node objects. For the lookup() operation, there is a BinaryTree.lookup() method that the client uses to start a lookup operation. Internal to the BinaryTree class, there is a private recursive lookup(Node) method that implements the recursion down the Node structure. This second, private recursive method is basically the same as the recursive C/C++ functions above -- it takes a Node argument and uses recursion to iterate over the pointer structure. &lt;br /&gt;&lt;h3&gt;Java Binary Tree Structure&lt;/h3&gt;To get started, here are the basic definitions for the Java BinaryTree class, and the lookup() and insert() methods as examples... &lt;br /&gt;&lt;tt&gt;// BinaryTree.java&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;public class BinaryTree {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  // Root node pointer. Will be null for an empty tree.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  private Node root;&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;tt&gt;  /*&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   --Node--&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   The binary tree is built using this nested node class.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   Each node stores one data element, and has left and right&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   sub-tree pointer which may be null.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   The node is a "dumb" nested class -- we just use it for&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   storage; it does not have any methods.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  */&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  private static class Node {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    Node left;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    Node right;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    int data;&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;    Node(int newData) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;      left = null;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;      right = null;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;      data = newData;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt;&lt;br /&gt;&lt;span style="font-family: monospace;"&gt;&lt;span style="font-family: 'Trebuchet MS', Verdana, Arial, sans-serif; font-size: 15px; line-height: 20px;"&gt;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: monospace;"&gt;&lt;span style="font-family: 'Trebuchet MS', Verdana, Arial, sans-serif; font-size: 15px; line-height: 20px;"&gt;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: monospace;"&gt;&lt;span style="font-family: 'Trebuchet MS', Verdana, Arial, sans-serif; font-size: 15px; line-height: 20px;"&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: monospace;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;&lt;tt&gt;  /**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   Creates an empty binary tree -- a null root pointer.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  */&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  public void BinaryTree() {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    root = null;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;tt&gt;  /**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   Returns true if the given target is in the binary tree.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   Uses a recursive helper.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  */&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  public boolean lookup(int data) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    return(lookup(root, data));&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;tt&gt;  /**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   Recursive lookup  -- given a node, recur&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   down searching for the given data.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  */&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  private boolean lookup(Node node, int data) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    if (node==null) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;      return(false);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    }&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;    if (data==node.data) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;      return(true);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    else if (data&lt;node.data)&gt;&lt;br /&gt;&lt;tt&gt;      return(lookup(node.left, data));&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    else {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;      return(lookup(node.right, data));&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt;&lt;br /&gt;&lt;/node.data)&gt;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;&lt;tt&gt;  /**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   Inserts the given data into the binary tree.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   Uses a recursive helper.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  */&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  public void insert(int data) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    root = insert(root, data);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;tt&gt;  /**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   Recursive insert -- given a node pointer, recur down and&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   insert the given data into the tree. Returns the new&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   node pointer (the standard way to communicate&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   a changed pointer back to the caller).&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  */&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  private Node insert(Node node, int data) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    if (node==null) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;      node = new Node(data);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    else {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;      if (data &amp;lt;= node.data) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;        node.left = insert(node.left, data);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;      }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;      else {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;        node.right = insert(node.right, data);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;      }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    }&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;    return(node); // in any case, return the new pointer to the caller&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;&lt;h3&gt;OOP Style vs. Recursive Style&lt;/h3&gt;From the client point of view, the BinaryTree class demonstrates good OOP style -- it encapsulates the binary tree state, and the client sends messages like lookup() and insert() to operate on that state. Internally, the Node class and the recursive methods &lt;b&gt;do not &lt;/b&gt;demonstrate OOP style. The recursive methods like insert(Node) and lookup (Node, int) basically look like recursive functions in any language. In particular, they do not operate against a "receiver" in any special way. Instead, the recursive methods operate on the arguments that are passed in which is the classical way to write recursion. My sense is that the OOP style and the recursive style do not be combined nicely for binary trees, so I have left them separate. Merging the two styles would be especially awkward for the "empty" tree (null) case, since you can't send a message to the null pointer. It's possible to get around that by having a special object to represent the null tree, but that seems like a distraction to me. I prefer to keep the recursive methods simple, and use different examples to teach OOP. &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Java Solutions&lt;/h3&gt;Here are the Java solutions to the 14 binary tree problems. Most of the solutions use two methods:a one-line OOP method that starts the computation, and a recursive method that does the real operation. Make an attempt to solve each problem before looking at the solution -- it's the best way to learn. &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;1. Build123() Solution (Java)&lt;/h3&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Build 123 using three pointer variables.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;public void build123a() {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  root = new Node(2);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  Node lChild = new Node(1);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  Node rChild = new Node(3);&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;  root.left = lChild;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  root.right= rChild;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Build 123 using only one pointer variable.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;public void build123b() {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  root = new Node(2);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  root.left = new Node(1);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  root.right = new Node(3);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Build 123 by calling insert() three times.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Note that the '2' must be inserted first.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;public void build123c() {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  root = null;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  root = insert(root, 2);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  root = insert(root, 1);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  root = insert(root, 3);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;2. size() Solution (Java)&lt;/h3&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Returns the number of nodes in the tree.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Uses a recursive helper that recurs&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; down the tree and counts the nodes.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;public int size() {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  return(size(root));&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;private int size(Node node) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  if (node == null) return(0);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  else {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    return(size(node.left) + 1 + size(node.right));&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;3. maxDepth() Solution (Java)&lt;/h3&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Returns the max root-to-leaf depth of the tree.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Uses a recursive helper that recurs down to find&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; the max depth.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;public int maxDepth() {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  return(maxDepth(root));&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;private int maxDepth(Node node) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  if (node==null) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    return(0);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  else {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    int lDepth = maxDepth(node.left);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    int rDepth = maxDepth(node.right);&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;    // use the larger + 1&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    return(Math.max(lDepth, rDepth) + 1);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;4. minValue() Solution (Java)&lt;/h3&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Returns the min value in a non-empty binary search tree.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Uses a helper method that iterates to the left to find&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; the min value.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;public int minValue() {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; return( minValue(root) );&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Finds the min value in a non-empty binary search tree.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;private int minValue(Node node) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  Node current = node;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  while (current.left != null) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    current = current.left;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;  return(current.data);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt; &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;5. printTree() Solution (Java)&lt;/h3&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Prints the node values in the "inorder" order.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Uses a recursive helper to do the traversal.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;public void printTree() {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; printTree(root);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; System.out.println();&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;private void printTree(Node node) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; if (node == null) return;&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt; // left, node itself, right&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; printTree(node.left);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; System.out.print(node.data + "  ");&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; printTree(node.right);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;6. printPostorder() Solution (Java)&lt;/h3&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Prints the node values in the "postorder" order.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Uses a recursive helper to do the traversal.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;public void printPostorder() {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; printPostorder(root);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; System.out.println();&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;public void printPostorder(Node node) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  if (node == null) return;&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;  // first recur on both subtrees&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  printPostorder(node.left);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  printPostorder(node.right);&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;  // then deal with the node&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; System.out.print(node.data + "  ");&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;7. hasPathSum() Solution (Java)&lt;/h3&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Given a tree and a sum, returns true if there is a path from the root&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; down to a leaf, such that adding up all the values along the path&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; equals the given sum.&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt; Strategy: subtract the node value from the sum when recurring down,&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; and check to see if the sum is 0 when you run out of tree.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;public boolean hasPathSum(int sum) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; return( hasPathSum(root, sum) );&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;boolean hasPathSum(Node node, int sum) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  // return true if we run out of tree and sum==0&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  if (node == null) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    return(sum == 0);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  else {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  // otherwise check both subtrees&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    int subSum = sum - node.data;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    return(hasPathSum(node.left, subSum) || hasPathSum(node.right, subSum));&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;8. printPaths() Solution (Java)&lt;/h3&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Given a binary tree, prints out all of its root-to-leaf&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; paths, one per line. Uses a recursive helper to do the work.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;public void printPaths() {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  int[] path = new int[1000];&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  printPaths(root, path, 0);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Recursive printPaths helper -- given a node, and an array containing&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; the path from the root node up to but not including this node,&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; prints out all the root-leaf paths.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;private void printPaths(Node node, int[] path, int pathLen) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  if (node==null) return;&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;  // append this node to the path array&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  path[pathLen] = node.data;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  pathLen++;&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;  // it's a leaf, so print the path that led to here&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  if (node.left==null &amp;amp;&amp;amp; node.right==null) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    printArray(path, pathLen);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  else {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  // otherwise try both subtrees&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    printPaths(node.left, path, pathLen);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    printPaths(node.right, path, pathLen);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Utility that prints ints from an array on one line.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;private void printArray(int[] ints, int len) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  int i;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  for (i=0; i&lt;len;&gt;&lt;br /&gt;&lt;tt&gt;   System.out.print(ints[i] + " ");&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  System.out.println();&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt;&lt;br /&gt;&lt;/len;&gt;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;&lt;h3&gt;9. mirror() Solution (Java)&lt;/h3&gt;&lt;br /&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Changes the tree into its mirror image.&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt; So the tree...&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;       4&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;      / \&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;     2   5&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    / \&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   1   3&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt; is changed to...&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;       4&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;      / \&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;     5   2&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;        / \&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;       3   1&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt; Uses a recursive helper that recurs over the tree,&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; swapping the left/right pointers.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;public void mirror() {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  mirror(root);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;private void mirror(Node node) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  if (node != null) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    // do the sub-trees&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    mirror(node.left);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    mirror(node.right);&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;    // swap the left/right pointers&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    Node temp = node.left;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    node.left = node.right;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    node.right = temp;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;10. doubleTree() Solution (Java)&lt;/h3&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Changes the tree by inserting a duplicate node&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; on each nodes's .left.&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;tt&gt; So the tree...&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    2&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   / \&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  1   3&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt; Is changed to...&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;       2&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;      / \&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;     2   3&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    /   /&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   1   3&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  /&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; 1&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt; Uses a recursive helper to recur over the tree&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; and insert the duplicates.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;public void doubleTree() {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; doubleTree(root);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;private void doubleTree(Node node) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  Node oldLeft;&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;  if (node == null) return;&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;  // do the subtrees&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  doubleTree(node.left);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  doubleTree(node.right);&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;  // duplicate this node to its left&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  oldLeft = node.left;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  node.left = new Node(node.data);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  node.left.left = oldLeft;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;11. sameTree() Solution (Java)&lt;/h3&gt;&lt;tt&gt;/*&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Compares the receiver to another tree to&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; see if they are structurally identical.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;public boolean sameTree(BinaryTree other) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; return( sameTree(root, other.root) );&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Recursive helper -- recurs down two trees in parallel,&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; checking to see if they are identical.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;boolean sameTree(Node a, Node b) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  // 1. both empty -&amp;gt; true&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  if (a==null &amp;amp;&amp;amp; b==null) return(true);&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;  // 2. both non-empty -&amp;gt; compare them&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  else if (a!=null &amp;amp;&amp;amp; b!=null) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    return(&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;      a.data == b.data &amp;amp;&amp;amp;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;      sameTree(a.left, b.left) &amp;amp;&amp;amp;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;      sameTree(a.right, b.right)&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    );&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  // 3. one empty, one not -&amp;gt; false&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  else return(false);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;12. countTrees() Solution (Java)&lt;/h3&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; For the key values 1...numKeys, how many structurally unique&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; binary search trees are possible that store those keys?&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt; Strategy: consider that each value could be the root.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Recursively find the size of the left and right subtrees.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;public static int countTrees(int numKeys) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  if (numKeys &amp;lt;=1) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    return(1);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  else {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    // there will be one value at the root, with whatever remains&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    // on the left and right each forming their own subtrees.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    // Iterate through all the values that could be the root...&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    int sum = 0;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    int left, right, root;&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;    for (root=1; root&amp;lt;=numKeys; root++) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;      left = countTrees(root-1);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;      right = countTrees(numKeys - root);&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;      // number of possible trees with this root == left*right&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;      sum += left*right;&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    }&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;    return(sum);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;13. isBST1() Solution (Java)&lt;/h3&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Tests if a tree meets the conditions to be a&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; binary search tree (BST).&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;public boolean isBST() {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  return(isBST(root));&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Recursive helper -- checks if a tree is a BST&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; using minValue() and maxValue() (not efficient).&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;private boolean isBST(Node node) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  if (node==null) return(true);&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;  // do the subtrees contain values that do not&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  // agree with the node?&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  if (node.left!=null &amp;amp;&amp;amp; maxValue(node.left) &amp;gt; node.data) return(false);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  if (node.right!=null &amp;amp;&amp;amp; minValue(node.right) &amp;lt;= node.data) return(false);&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;  // check that the subtrees themselves are ok&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  return( isBST(node.left) &amp;amp;&amp;amp; isBST(node.right) );&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;14. isBST2() Solution (Java)&lt;/h3&gt;&lt;/tt&gt;&lt;/tt&gt;&lt;tt&gt;&lt;tt&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; Tests if a tree meets the conditions to be a&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; binary search tree (BST). Uses the efficient&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; recursive helper.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;public boolean isBST2() {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt; return( isBST2(root, Integer.MIN_VALUE, Integer.MAX_VALUE) );&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;/**&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  Efficient BST helper -- Given a node, and min and max values,&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  recurs down the tree to verify that it is a BST, and that all&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  its nodes are within the min..max range. Works in O(n) time --&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  visits each node only once.&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;*/&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;private boolean isBST2(Node node, int min, int max) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  if (node==null) {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    return(true);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  else {&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;   // left should be in range  min...node.data&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    boolean leftOk = isBST2(node.left, min, node.data);&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;    // if the left is not ok, bail out&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    if (!leftOk) return(false);&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;    // right should be in range node.data+1..max&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;    boolean rightOk = isBST2(node.right, node.data+1, max);&lt;/tt&gt; &lt;br /&gt;&lt;tt&gt;    return(rightOk);&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;  }&lt;/tt&gt;&lt;br /&gt;&lt;tt&gt;}&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;by Nick Parlante&lt;br /&gt;&lt;br /&gt;&lt;/tt&gt;&lt;/tt&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-4496048897337051889?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/4496048897337051889/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/12/binary-trees.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/4496048897337051889'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/4496048897337051889'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/12/binary-trees.html' title='Binary Trees'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-6027706051393286934</id><published>2009-12-03T23:33:00.000-08:00</published><updated>2009-12-13T04:38:50.440-08:00</updated><title type='text'>Java, sorting, ArrayList example, generics</title><content type='html'>&lt;span style="-webkit-border-horizontal-spacing: 2px; -webkit-border-vertical-spacing: 2px; font-family: Arial, Helvetica, sans-serif; font-size: 12px; line-height: 14px;"&gt;A Java &lt;b&gt;ArrayList&lt;/b&gt; holds an ordered sequence of items like an array, but there are differences:&lt;br /&gt;&lt;br /&gt;1. An ArrayList has no fixed size but can be extended by adding elements later&lt;br /&gt;2. An ArrayList can only hold objects (not primitives)&lt;br /&gt;3. ArrayList elements are addressed by methods and not by square bracket notation.&lt;br /&gt;&lt;br /&gt;Here's an example from yesterday - showing a typical use of an ArrayList; I was reading a file but didn't know how many lines it contained, so an ArrayList gave me the flexibility I needed.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;import java.io.*;&lt;br /&gt;import java.util.*;&lt;br /&gt;&lt;br /&gt;public class Pesort {&lt;br /&gt;&lt;br /&gt;public static void main (String [] args) throws Exception {&lt;br /&gt;&lt;br /&gt;// Following line up to Java 1.4 then gives warnings&lt;br /&gt;//ArrayList Stuff = new ArrayList();&lt;br /&gt;&lt;br /&gt;// OR following line from Java 1.5;&lt;br /&gt;// this specifies that the ArrayList is to contain Strings&lt;br /&gt;&lt;br /&gt;ArrayList &lt;string&gt; Stuff = new ArrayList&lt;string&gt;();&lt;br /&gt;&lt;br /&gt;// Above lines show use of "Generics" - compare to&lt;br /&gt;// Templates in C++&lt;br /&gt;&lt;br /&gt;BufferedReader Source = new BufferedReader(&lt;br /&gt;new FileReader("../request.txt"));&lt;br /&gt;&lt;br /&gt;System.out.println("---------- UnSorted");&lt;br /&gt;&lt;br /&gt;while (Source.ready() ) {&lt;br /&gt;String Line = Source.readLine();  &lt;br /&gt;System.out.println(Line);&lt;br /&gt;Stuff.add(Line);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;System.out.println("---------- Alphabetic Sort");&lt;br /&gt;&lt;br /&gt;Collections.sort(Stuff);&lt;br /&gt;&lt;br /&gt;Iterator stepper = Stuff.iterator();&lt;br /&gt;while (stepper.hasNext()) {&lt;br /&gt;String current = (String)stepper.next();&lt;br /&gt;System.out.println(current);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;System.out.println("---------- Sort by line length");&lt;br /&gt;&lt;br /&gt;Collections.sort(Stuff, new byLineLength());&lt;br /&gt;&lt;br /&gt;stepper = Stuff.iterator();&lt;br /&gt;while (stepper.hasNext()) {&lt;br /&gt;String current = (String)stepper.next();&lt;br /&gt;System.out.println(current);&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/string&gt;&lt;/string&gt;&lt;/code&gt;&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="-webkit-border-horizontal-spacing: 2px; -webkit-border-vertical-spacing: 2px; font-family: Arial, Helvetica, sans-serif; font-size: 12px; line-height: 14px;"&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;Here are the results from running that program:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;[trainee@snowdrop java08]$ java Pesort&lt;br /&gt;---------- UnSorted&lt;br /&gt;antonia Perl XML PHP Tcl/Tk MySQL&lt;br /&gt;barbara Tcl/Tk ASP Ruby Java&lt;br /&gt;cherry Perl Java Ruby MySQL&lt;br /&gt;delia XML PHP Java ASP&lt;br /&gt;florence Ruby PHP Java ASP&lt;br /&gt;gloria XML Perl Tcl/Tk MySQL&lt;br /&gt;zoe Ruby ASP Perl PHP&lt;br /&gt;adam Tcl/Tk Perl Python MySQL&lt;br /&gt;barry Python XML Java Perl PHP&lt;br /&gt;charles Perl Ruby MySQL Tcl/Tk&lt;br /&gt;ed Ruby Perl Java PHP&lt;br /&gt;fred MySQL Perl Java XML&lt;br /&gt;graham Java Perl Tcl/Tk&lt;br /&gt;harry PHP Python Java&lt;br /&gt;ivan Ruby Java Perl Tcl/Tk MySQL&lt;br /&gt;victor Ruby Perl Tcl/Tk MySQL&lt;br /&gt;william Ruby Perl PHP&lt;br /&gt;xavier PHP Java Perl&lt;br /&gt;yuri XML PHP Perl Tcl/Tk&lt;br /&gt;zachary MySQL Java Tcl/Tk&lt;br /&gt;---------- Alphabetic Sort&lt;br /&gt;adam Tcl/Tk Perl Python MySQL&lt;br /&gt;antonia Perl XML PHP Tcl/Tk MySQL&lt;br /&gt;barbara Tcl/Tk ASP Ruby Java&lt;br /&gt;barry Python XML Java Perl PHP&lt;br /&gt;charles Perl Ruby MySQL Tcl/Tk&lt;br /&gt;cherry Perl Java Ruby MySQL&lt;br /&gt;delia XML PHP Java ASP&lt;br /&gt;ed Ruby Perl Java PHP&lt;br /&gt;florence Ruby PHP Java ASP&lt;br /&gt;fred MySQL Perl Java XML&lt;br /&gt;gloria XML Perl Tcl/Tk MySQL&lt;br /&gt;graham Java Perl Tcl/Tk&lt;br /&gt;harry PHP Python Java&lt;br /&gt;ivan Ruby Java Perl Tcl/Tk MySQL&lt;br /&gt;victor Ruby Perl Tcl/Tk MySQL&lt;br /&gt;william Ruby Perl PHP&lt;br /&gt;xavier PHP Java Perl&lt;br /&gt;yuri XML PHP Perl Tcl/Tk&lt;br /&gt;zachary MySQL Java Tcl/Tk&lt;br /&gt;zoe Ruby ASP Perl PHP&lt;br /&gt;---------- Sort by line length&lt;br /&gt;xavier PHP Java Perl&lt;br /&gt;ed Ruby Perl Java PHP&lt;br /&gt;harry PHP Python Java&lt;br /&gt;william Ruby Perl PHP&lt;br /&gt;zoe Ruby ASP Perl PHP&lt;br /&gt;delia XML PHP Java ASP&lt;br /&gt;graham Java Perl Tcl/Tk&lt;br /&gt;fred MySQL Perl Java XML&lt;br /&gt;yuri XML PHP Perl Tcl/Tk&lt;br /&gt;zachary MySQL Java Tcl/Tk&lt;br /&gt;florence Ruby PHP Java ASP&lt;br /&gt;cherry Perl Java Ruby MySQL&lt;br /&gt;barbara Tcl/Tk ASP Ruby Java&lt;br /&gt;gloria XML Perl Tcl/Tk MySQL&lt;br /&gt;adam Tcl/Tk Perl Python MySQL&lt;br /&gt;victor Ruby Perl Tcl/Tk MySQL&lt;br /&gt;barry Python XML Java Perl PHP&lt;br /&gt;charles Perl Ruby MySQL Tcl/Tk&lt;br /&gt;ivan Ruby Java Perl Tcl/Tk MySQL&lt;br /&gt;antonia Perl XML PHP Tcl/Tk MySQL&lt;br /&gt;[trainee@snowdrop java08]$ &lt;/code&gt;&lt;br /&gt;&lt;br /&gt;And here is the comparator class that I wrote for my non-standard sort. Using a comparator class, the programmer can provide a method which is used internally by the sort method to compare two items and return an integer - negative, nought or positive - to indicate if the first object comes first in sequence, the objects have the same tank, or it comes second.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;public class byLineLength implements java.util.Comparator {&lt;br /&gt;public int compare(Object boy, Object girl) {&lt;br /&gt;int sdif = ((String)boy).length() - ((String)girl).length();&lt;br /&gt;return sdif;&lt;br /&gt;}&lt;br /&gt;}&lt;/code&gt; &lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-6027706051393286934?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/6027706051393286934/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/12/java-sorting-arraylist-example-generics.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/6027706051393286934'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/6027706051393286934'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/12/java-sorting-arraylist-example-generics.html' title='Java, sorting, ArrayList example, generics'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-2075266813611959493</id><published>2009-12-01T00:10:00.001-08:00</published><updated>2009-12-01T00:10:59.966-08:00</updated><title type='text'>partitioning sorting code</title><content type='html'>public int partition(int left, int right, int pivot) &lt;br /&gt;{ &lt;br /&gt;  int leftIdx = left -1; &lt;br /&gt;  int rightIdx = right + 1; &lt;br /&gt;  while (true) &lt;br /&gt;  { &lt;br /&gt;    while(leftIdx &lt; right &amp;&amp; data[++leftIdx] &lt; pivot) &lt;br /&gt;      ; //No operation, just increase the pointer &lt;br /&gt;    while( rightIdx &gt; left &amp;&amp; data[--rightIdx]&gt;pivot) &lt;br /&gt;      ; &lt;br /&gt;    if(leftIdx &gt;= rightIdx) &lt;br /&gt;      break; &lt;br /&gt;    else &lt;br /&gt;      swap(leftIdx, rightIdx); &lt;br /&gt;  } &lt;br /&gt;  return leftIdx; &lt;br /&gt;}&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-2075266813611959493?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/2075266813611959493/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/12/partitioning-sorting-code.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/2075266813611959493'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/2075266813611959493'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/12/partitioning-sorting-code.html' title='partitioning sorting code'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-2476846530915674077</id><published>2009-12-01T00:09:00.000-08:00</published><updated>2009-12-01T00:10:27.799-08:00</updated><title type='text'>shell sorting code</title><content type='html'>public void shellSort() &lt;br /&gt;{ &lt;br /&gt;  int inner, outer; &lt;br /&gt;  int temp; &lt;br /&gt;   &lt;br /&gt;  //Knuth’s recursion for initial interval sequence  &lt;br /&gt;  int h = 1; &lt;br /&gt;  while(h&lt;=aSize/3) &lt;br /&gt;    h = h*3 + 1; &lt;br /&gt;   &lt;br /&gt;  //At each gap interval step  &lt;br /&gt;  while(h&gt;0) &lt;br /&gt;  { &lt;br /&gt;    //Arrange each subset with insertion sorting &lt;br /&gt;    //Start comparing the second element of the  &lt;br /&gt;    //subset to the first one &lt;br /&gt;    for(outer=h;outer&lt;aSize; outer++) &lt;br /&gt;    { &lt;br /&gt;      //Make a copy of the first element &lt;br /&gt;      //not yet sorted &lt;br /&gt;      temp = data[outer]; &lt;br /&gt;      inner = outer;  &lt;br /&gt; &lt;br /&gt;      //And compare to all elements of the same  &lt;br /&gt;      //subset that have been sorted already &lt;br /&gt;      while(inner &gt; h-1 &amp;&amp; data[inner – h] &gt;= temp) &lt;br /&gt;      { &lt;br /&gt;        //move bigger values forward h steps &lt;br /&gt;        data[inner] = data[inner - h]; &lt;br /&gt;        inner -= h; &lt;br /&gt;      } &lt;br /&gt;      //and insert the not sorted element on its &lt;br /&gt;place &lt;br /&gt;      data[inner] = temp; &lt;br /&gt;    } &lt;br /&gt;    //Next interval in the sequence &lt;br /&gt;    h = (h-1)/3; &lt;br /&gt;  } &lt;br /&gt;}&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-2476846530915674077?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/2476846530915674077/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/12/shell-sorting-code.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/2476846530915674077'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/2476846530915674077'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/12/shell-sorting-code.html' title='shell sorting code'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-326687164091979948</id><published>2009-12-01T00:08:00.000-08:00</published><updated>2009-12-01T00:09:09.642-08:00</updated><title type='text'>insertion code</title><content type='html'>The algorithm implementation for the Java Array class could be like the following: &lt;br /&gt;public void insertionSort() &lt;br /&gt;{ &lt;br /&gt;  int i,j; &lt;br /&gt;  for(i=1; i&lt;aSize;i++) &lt;br /&gt;  { &lt;br /&gt;    int temp = data[i]; &lt;br /&gt;    j = i; &lt;br /&gt;    while (j&gt;0 &amp;&amp; data[j-1] &gt;= temp) &lt;br /&gt;    { &lt;br /&gt;      data[j] = data[j-1]; &lt;br /&gt;      --j; &lt;br /&gt;    } &lt;br /&gt;    data[j]=temp; &lt;br /&gt;  } &lt;br /&gt;}&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-326687164091979948?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/326687164091979948/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/12/insertion-code.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/326687164091979948'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/326687164091979948'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/12/insertion-code.html' title='insertion code'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-1837853649906704802</id><published>2009-12-01T00:07:00.002-08:00</published><updated>2009-12-16T05:53:34.376-08:00</updated><title type='text'>selection sort code</title><content type='html'>The implementation of the selection sort algorithm in our Array class could look like this:&lt;br /&gt;public void selectSort()&lt;br /&gt;{&lt;br /&gt;int i,j,min;&lt;br /&gt;for (i=0;i&lt;asize-1;i++)//for each="" element=""&gt;&lt;br /&gt;{&lt;br /&gt;min=i; //The first element is the first minimum&lt;br /&gt;&lt;br /&gt;for (j = i+1;j&lt;asize;j++)&gt;&lt;br /&gt;&lt;br /&gt;if(data[j] &amp;lt; data[min])//if new item smaller&lt;br /&gt;&lt;br /&gt;min = j;//It is the new minimum&lt;br /&gt;&lt;br /&gt;swap(i,min);&lt;br /&gt;}&lt;br /&gt;}&lt;/asize;j++)&gt;&lt;/asize-1;i++)//for&gt;&lt;br /&gt;&lt;br /&gt;or you can see example from this video from youtube&lt;br /&gt;&lt;span class="Apple-style-span"  style="color:#FF0000;"&gt;&lt;a href="http://www.youtube.com/watch?v=pAwibOhB1Gw"&gt;watch me&lt;/a&gt;&lt;/span&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-1837853649906704802?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/1837853649906704802/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/12/selection-sort-code.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/1837853649906704802'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/1837853649906704802'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/12/selection-sort-code.html' title='selection sort code'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-6991175314236374041</id><published>2009-12-01T00:07:00.001-08:00</published><updated>2009-12-01T00:07:52.491-08:00</updated><title type='text'>bubble sort code</title><content type='html'>The bubble sort algorithm for an integer array class with Java language is presented below. The &lt;br /&gt;sorting algorithm applies the private method swap in the operation. &lt;br /&gt;public void bubbleSort() &lt;br /&gt;{ &lt;br /&gt;  int i,j; &lt;br /&gt;  for (i=aSize; i&gt;1; i--) &lt;br /&gt;    for(j=0;j&lt;i;j++) &lt;br /&gt;      if(array[j] &gt; array[j+1]) &lt;br /&gt;        swap(j,j+1); &lt;br /&gt;} &lt;br /&gt;   &lt;br /&gt;private void swap(int i, int j) &lt;br /&gt;{ &lt;br /&gt;  int temp = array[i]; &lt;br /&gt;  array[i] = array[j]; &lt;br /&gt;  array[j] = temp; &lt;br /&gt;}&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-6991175314236374041?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/6991175314236374041/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/12/bubble-sort-code.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/6991175314236374041'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/6991175314236374041'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/12/bubble-sort-code.html' title='bubble sort code'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-7702494685728303089</id><published>2009-11-30T12:19:00.001-08:00</published><updated>2009-11-30T12:19:44.194-08:00</updated><title type='text'>Collections methods</title><content type='html'>&lt;p&gt;The &lt;code&gt;java.util.Collections&lt;/code&gt; class contains &lt;b&gt;static&lt;/b&gt; utility methods for manipulating collections. &lt;/p&gt;  &lt;h2&gt;Some useful Collections methods&lt;/h2&gt; &lt;p&gt;Assume the following declarations have been made, where &lt;code&gt;T&lt;/code&gt; is a class or interface type. &lt;/p&gt; &lt;pre class="fragment"&gt;   int i;&lt;br /&gt;  List&lt;t&gt; listC;   // List of the Comparable objects.&lt;br /&gt;  List&lt;t&gt; list;    // Any kind of list.  Need not be Comparable.&lt;br /&gt;  Comparator&lt;t&gt; comp;&lt;br /&gt;  T key;&lt;br /&gt;  T t;&lt;br /&gt;  Collection&lt;t&gt; coll;  // Any kind of Collection (List, Set, Deque).&lt;br /&gt;  Collection&lt;t&gt; collC; // Any kind of Collection implementing Comparable. &lt;/pre&gt;  &lt;table summary="Collection methods" border="0" cellspacing="0"&gt; &lt;tbody&gt;&lt;tr&gt;&lt;td colspan="3" class="rowheader"&gt;&lt;i&gt;Rearranging - Sorting, Shuffling, . . .&lt;/i&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt; &lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Collections.&lt;b&gt;sort&lt;/b&gt;(listC)&lt;/code&gt;&lt;/td&gt;                  &lt;td&gt;Sorts &lt;code&gt;listC&lt;/code&gt;. Elements must be &lt;i&gt;Comparable&lt;t&gt;&lt;/i&gt;.  Stable, O(N log N).&lt;/td&gt;&lt;/tr&gt;                   &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt; &lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Collections.&lt;b&gt;sort&lt;/b&gt;(list, comp)&lt;/code&gt;&lt;/td&gt;                  &lt;td&gt;Sorts &lt;code&gt;list&lt;/code&gt; using a comparator.&lt;/td&gt;&lt;/tr&gt;                   &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt; &lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Collections.&lt;b&gt;shuffle&lt;/b&gt;(list)&lt;/code&gt;&lt;/td&gt;                  &lt;td&gt;Puts the elements of &lt;code&gt;list&lt;/code&gt; in random order.&lt;/td&gt;&lt;/tr&gt;                   &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt; &lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Collections.&lt;b&gt;reverse&lt;/b&gt;(list)&lt;/code&gt;&lt;/td&gt;                  &lt;td&gt;Reverses the elements of &lt;code&gt;list&lt;/code&gt;.&lt;/td&gt;&lt;/tr&gt;                   &lt;tr&gt;&lt;td colspan="3" class="rowheader"&gt;&lt;i&gt;Searching&lt;/i&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt;i = &lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Collections.&lt;b&gt;binarySearch&lt;/b&gt;(listC, key)&lt;/code&gt;&lt;/td&gt;                  &lt;td&gt;Searches &lt;code&gt;list&lt;/code&gt; for &lt;code&gt;key&lt;/code&gt;.                  Returns index of element or negative value if not found.                  See &lt;a href="http://leepoint.net/notes-java/algorithms/searching/binarysearch.html"&gt;Binary Search&lt;/a&gt;.&lt;/td&gt;&lt;/tr&gt;                   &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt;i = &lt;/code&gt;&lt;/td&gt;&lt;td nowrap="nowrap"&gt;&lt;code&gt;Collections.&lt;b&gt;binarySearch&lt;/b&gt;(list, key, comp)&lt;/code&gt;&lt;/td&gt;                  &lt;td&gt;Searches in &lt;code&gt;list&lt;/code&gt; for &lt;code&gt;key&lt;/code&gt; using Comparator comp.&lt;/td&gt;&lt;/tr&gt;                   &lt;tr valign="top"&gt;&lt;td align="right" nowrap="nowrap"&gt;&lt;code&gt;t = &lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Collections.&lt;b&gt;max&lt;/b&gt;(collC)&lt;/code&gt;&lt;/td&gt;                  &lt;td&gt;Returns maximum valued &lt;i&gt;Comparable&lt;/i&gt; object in &lt;code&gt;collC&lt;/code&gt;.&lt;/td&gt;&lt;/tr&gt;                   &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt;t = &lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Collections.&lt;b&gt;max&lt;/b&gt;(coll, comp)&lt;/code&gt;&lt;/td&gt;                  &lt;td&gt;Maximum valued object in &lt;code&gt;coll&lt;/code&gt;                  using Comparator &lt;code&gt;comp&lt;/code&gt;.&lt;/td&gt;&lt;/tr&gt;                   &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt;t = &lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Collections.&lt;b&gt;min&lt;/b&gt;(collC)&lt;/code&gt;&lt;/td&gt;                  &lt;td&gt;Returns minimum valued &lt;i&gt;Comparable&lt;/i&gt; object in &lt;code&gt;collC&lt;/code&gt;.&lt;/td&gt;&lt;/tr&gt;                   &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt;t = &lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Collections.&lt;b&gt;min&lt;/b&gt;(coll, comp)&lt;/code&gt;&lt;/td&gt;                  &lt;td&gt;Minimum valued object in &lt;code&gt;coll&lt;/code&gt;                  using Comparator &lt;code&gt;comp&lt;/code&gt;.&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt;&lt;/table&gt;  &lt;p&gt;There are many additional methods in Collections, but the above are a good start. &lt;/p&gt;   &lt;h2&gt;Searching may also be implemented in data structure classes&lt;/h2&gt; &lt;p&gt;All &lt;i&gt;List&lt;/i&gt; and &lt;i&gt;Set&lt;/i&gt; classes implement the &lt;code&gt;contains()&lt;/code&gt; method,  which performes a linear search on lists (O(N)), a binary search for TreeSets (O(log N)),  and a hashed search for HashSets (O(1)). &lt;/p&gt; &lt;p&gt;Maps define &lt;code&gt;get()&lt;/code&gt; to search for the key. For HashMaps the search is O(1), and for TreeMaps the search is O(log N).&lt;/p&gt;    &lt;h2&gt;Sorting may be implicit in a data structure class&lt;/h2&gt;  &lt;p&gt;TreeSet data and TreeMap keys are sorted at all times.   They are implemented as binary trees, so insertion and search are both O(log N).   An iterator can be used to get retrieve the data (TreeSets) or keys (TreeMaps) in sorted order.  Either the element class must be &lt;i&gt;Comparable&lt;/i&gt;, or  a &lt;i&gt;Comparator&lt;/i&gt; must be supplied.&lt;/p&gt;   &lt;div class="footer"&gt; Copyleft 2006 &lt;a href="http://www.fredosaurus.com/"&gt;Fred Swartz&lt;/a&gt; &lt;a href="http://www.opensource.org/licenses/mit-license.php"&gt;MIT License&lt;/a&gt; &lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-7702494685728303089?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/7702494685728303089/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/11/collections-methods.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/7702494685728303089'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/7702494685728303089'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/11/collections-methods.html' title='Collections methods'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-7444643803065690701</id><published>2009-11-30T12:17:00.001-08:00</published><updated>2009-11-30T12:17:52.781-08:00</updated><title type='text'></title><content type='html'>&lt;h1&gt;Array Library Methods&lt;/h1&gt;  &lt;p&gt;Static methods for manipulating arrays are available in the &lt;code&gt;java.util.Arrays&lt;/code&gt; and &lt;code&gt;java.System&lt;/code&gt; classes. Assume the following declarations, where &lt;code&gt;T&lt;/code&gt; is the array element type, either a primitive, object or either kind of type depending on which method is being called. &lt;/p&gt; &lt;pre class="fragment"&gt;T       x, key;  // This type T can be either a primitive or object type.&lt;br /&gt;T[]     a, a2;   // This type T can be either a primitive or object type.&lt;br /&gt;List&lt;t&gt; lst;     // Only object types T.&lt;br /&gt;Comparator&lt;? super T&gt; comp;  // Only object types T.&lt;br /&gt;int     i;    // Index returned from search.&lt;br /&gt;int     i1, i2;&lt;br /&gt;int     from; // Lower bound of subscript range.  Includes this element.&lt;br /&gt;int     to;   // Upper bound of subscript range.  Does not include this element.&lt;br /&gt;String  s;&lt;br /&gt;boolean b;  // Normally the method result will be used in an &lt;i&gt;if&lt;/i&gt;.&lt;br /&gt;&lt;/pre&gt; &lt;table&gt; &lt;tbody&gt;&lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt;lst = &lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Arrays.asList(a);&lt;/code&gt;  &lt;/td&gt;&lt;td&gt;List based on the array.&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt;  s = &lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Arrays.toString(a);&lt;/code&gt;&lt;/td&gt;&lt;td&gt;String form surrounded by "[]", elements separated by ", ".&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt;  s = &lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Arrays.deepToString(a);&lt;/code&gt;&lt;/td&gt;&lt;td&gt;String form by recursively converting subarrays.&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt;  b = &lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Arrays.equals(a, a2);&lt;/code&gt;&lt;/td&gt;&lt;td&gt;True if arrays are same size and all elements are equal (== or equals as appropriate).&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt;  b = &lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Arrays.deepEquals(a, a2);&lt;/code&gt;&lt;/td&gt;&lt;td&gt;As above, recursively applied to subarrays.&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt;      &lt;/code&gt;&lt;br /&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Arrays.fill(a, x);&lt;/code&gt;  &lt;/td&gt;&lt;td&gt;Fills array with a value.&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt;      &lt;/code&gt;&lt;br /&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Arrays.fill(a, from, to, x);&lt;/code&gt;  &lt;/td&gt;&lt;td&gt;Fills subrange (&lt;i&gt;from&lt;/i&gt; inclusive, &lt;i&gt;to&lt;/i&gt; exclusive) with a value.&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td colspan="3" class="rowheader"&gt;Making a copy of part of an array&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt;      &lt;/code&gt;&lt;br /&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;System.arraycopy(a, i1, a2, i2, len);&lt;/code&gt;  &lt;/td&gt;&lt;td&gt;Shallow copy &lt;i&gt;len&lt;/i&gt; elements from &lt;code&gt;a[i1]&lt;/code&gt; to &lt;code&gt;a2[i2]&lt;/code&gt;.  Case!&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt; a2 = &lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Arrays.copyOf(a, newLength);&lt;/code&gt;      &lt;/td&gt;&lt;td&gt;New shallow copy of array with new length.  If longer, uses default values.&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt; a2 = &lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Arrays.copyOfRange(a, from, to);&lt;/code&gt;  &lt;/td&gt;&lt;td&gt;New shallow copy of portion of array.&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td colspan="3" class="rowheader"&gt;Searching&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt;  i = &lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Arrays.binarySearch(a, key);&lt;/code&gt;&lt;/td&gt;&lt;td&gt;A O(log N)search of array sorted in ascending order. If the key is not found, a negative number, -insertionPoint-1, is returned.&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt;  i = &lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Arrays.binarySearch(a, key, comp);&lt;/code&gt;&lt;/td&gt;&lt;td&gt;Binary search of a sorted array of objects (not primitives).&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td colspan="3" class="rowheader"&gt;&lt;br /&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt;      &lt;/code&gt;&lt;br /&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Arrays.sort(a);&lt;/code&gt;                &lt;/td&gt;&lt;td&gt;Sorts in "natural" order.  If object type, elements must be &lt;i&gt;comparable&lt;/i&gt;.&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt;      &lt;/code&gt;&lt;br /&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Arrays.sort(a, comp);&lt;/code&gt;          &lt;/td&gt;&lt;td&gt;Sorts objects (not primitives) using comparator.&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt;      &lt;/code&gt;&lt;br /&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Arrays.sort(a, from, to);&lt;/code&gt;      &lt;/td&gt;&lt;td&gt;Sorts subrange, including &lt;code&gt;a[from]&lt;/code&gt; excluding &lt;code&gt;a[to]&lt;/code&gt;.&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td align="right"&gt;&lt;code&gt;      &lt;/code&gt;&lt;br /&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;Arrays.sort(a, from, to, comp);&lt;/code&gt;&lt;/td&gt;&lt;td&gt;Sorts objects (not primitives) in subrange using comparator.&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt;&lt;/table&gt;    &lt;h2&gt;Use &lt;code&gt;java.util.Arrays.toString(...)&lt;/code&gt; for debugging&lt;/h2&gt; &lt;p&gt;&lt;b&gt;AVOID default toString()&lt;/b&gt;.  Using the common debugging technique of printing intermediate values on the console with arrays is good, but requires calling a library method to get the results you expect. Arrays are a subclass of &lt;code&gt;Object&lt;/code&gt; as ever other object is, and therefore the &lt;code&gt;toString()&lt;/code&gt; method is defined for every array.  The results will very likely disappoint you. &lt;/p&gt; &lt;pre class="fragmentBox"&gt;String[] abc = {"a", "b", "c"};&lt;br /&gt;System.out.println(abc);   // println calls toString() on object parameters.&lt;br /&gt;&lt;/pre&gt; &lt;p&gt;This displays the relatively unhelpful "[L", element type, ";@", and  hexadecimal memory address of the array.&lt;/p&gt; &lt;pre class="fragment"&gt;[Ljava.lang.String;@f6f1b6&lt;br /&gt;&lt;/pre&gt;  &lt;p&gt;&lt;b&gt;USE &lt;code&gt;java.util.Arrays.toString(...)&lt;/code&gt;&lt;/b&gt; and you'll get something much more readable. An &lt;code&gt;import java.util.*;&lt;/code&gt; statement avoids the extra package qualifier.&lt;/p&gt;  &lt;pre class="fragmentBox"&gt;String[] abc = {"a", "b", "c"};&lt;br /&gt;System.out.println(&lt;span class="hilite"&gt;java.util.Arrays.toString(abc)&lt;/span&gt;);&lt;br /&gt;&lt;/pre&gt; &lt;p&gt;This produces the following output, which is the same as &lt;code&gt;toString()&lt;/code&gt; applied to a &lt;i&gt;List&lt;/i&gt;.&lt;/p&gt; &lt;pre class="fragment"&gt;[a, b, c]&lt;br /&gt;&lt;/pre&gt;    &lt;h2&gt;Use &lt;code&gt;Arrays.asList(...)&lt;/code&gt; for Collections view of array&lt;/h2&gt; &lt;p&gt;&lt;b&gt;Make a list&lt;/b&gt;.  The &lt;code&gt;Arrays&lt;/code&gt; class has some useful methods for working with arrays, but there are a lot more if you make your array look like a &lt;i&gt;List&lt;/i&gt;.  The Collections class has many useful methods, eg,  shuffle, reverse, max, ....&lt;/p&gt;  &lt;pre class="fragmentBox"&gt;import java.util.*;&lt;br /&gt;   . . .&lt;br /&gt;   List&lt;string&gt; listabc = &lt;span class="hilite"&gt;Arrays.asList(abc)&lt;/span&gt;; &lt;br /&gt;   // The Collections methods can now be use with &lt;i&gt;listabc&lt;/i&gt;.&lt;br /&gt;&lt;/pre&gt;  &lt;p&gt;&lt;b&gt;View of underlying array&lt;/b&gt;.  The list that is created is not a regular  &lt;code&gt;ArrayList&lt;/code&gt;.  It is based only on the original array, so you can't do things like adding elements to the list because this would cause reallocation of a larger underlying array. &lt;/p&gt;  &lt;p&gt;&lt;b&gt;Uses the underlying array&lt;/b&gt;.  One of the really nice things about this is that you can still use the underlying array, which means that creating this list doesn't prevent you from taking advantage of the efficiency of array access for example. &lt;/p&gt;  &lt;p&gt;&lt;b&gt;Objects only&lt;/b&gt;.  The &lt;code&gt;java.util.Arrays.asList(...)&lt;/code&gt; method only works for arrays of object types.  If you try to use it with an array of primitives, you will get a compilation error. &lt;/p&gt;    &lt;h2&gt;Shuffling (randomizing) an array&lt;/h2&gt; &lt;div class="fragmentBox"&gt;&lt;pre&gt;import java.util.*;&lt;br /&gt;. . .&lt;br /&gt;   List&lt;string&gt; labc = &lt;span class="hilite"&gt;Arrays.asList(abc)&lt;/span&gt;;&lt;br /&gt;   . . .&lt;br /&gt;   &lt;span class="hilite"&gt;Collections.shuffle(labc)&lt;/span&gt;;&lt;br /&gt;   System.out.println(labc);&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;p&gt;Which gave the following output.  Note that the &lt;code&gt;List&lt;/code&gt; overrides &lt;code&gt;toString()&lt;/code&gt; to give reasonable output.&lt;/p&gt;  &lt;pre class="fragment"&gt;[b, a, c]&lt;br /&gt;&lt;/pre&gt;  &lt;p&gt;&lt;b&gt;Inefficient? Not necessarily.&lt;/b&gt;  Constructing a  new List object from the array is only inefficient if you're doing it frequently.   If you do it very often then you want to avoid creating a new list each time. Creating the list one time is not a problem because the list that is produced is backed by this one array -- you can change elements in the array and the list will reflect those changes.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-7444643803065690701?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/7444643803065690701/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/11/array-library-methods-static-methods.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/7444643803065690701'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/7444643803065690701'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/11/array-library-methods-static-methods.html' title=''/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-6753984746904437281</id><published>2009-11-30T12:16:00.000-08:00</published><updated>2009-11-30T12:20:46.513-08:00</updated><title type='text'>Searching and Sorting Overview</title><content type='html'>&lt;h2&gt;Why searching and sorting are often treated together&lt;/h2&gt; &lt;p&gt;Searching and sorting algorithms are  often grouped together for a couple of reasons. &lt;/p&gt; &lt;ul&gt;&lt;li&gt;Comparisons are used by both types of algorithms.&lt;/li&gt;&lt;li&gt;Searching often requires a data structure that is already sorted.&lt;/li&gt;&lt;li&gt;Searching and sorting are common operations on data structures.&lt;/li&gt;&lt;/ul&gt;   &lt;h2&gt;Comparing 3 ways - Operators, Comparable, Comparator&lt;/h2&gt; &lt;b&gt;Comparisons&lt;/b&gt; are at the heart of both searching and sorting.     Comparison turns out not to be quite as simple as it first     appears to be.  There are three ways values can be compared.     &lt;ul&gt;&lt;li&gt;&lt;b&gt;Comparison operators&lt;/b&gt; (&lt;code&gt;&lt; &lt;= == != &gt;= &gt;&lt;/code&gt;) for primitive values.     &lt;pre class="fragment"&gt;    if (a &lt;&gt;     &lt;/pre&gt;&lt;/li&gt;&lt;li&gt;&lt;b&gt;Implementing the &lt;code&gt;Comparable&lt;/code&gt; interface&lt;/b&gt;         requires defining a &lt;code&gt;compare()&lt;/code&gt; method.         Java classes that have a &lt;i&gt;natural&lt;/i&gt; sorting order (eg, &lt;code&gt;String&lt;/code&gt;)         often implement &lt;i&gt;Comparable&lt;/i&gt;.         That &lt;i&gt;Comparable&lt;/i&gt; is implemented as an instance method         of the class that is being compared (in contrast to &lt;i&gt;Comparator&lt;/i&gt;).     &lt;pre class="fragment"&gt;    if (s.compareTo(t) &lt;&gt;         &lt;/pre&gt;&lt;/li&gt;&lt;li&gt;&lt;b&gt;Implementing the &lt;code&gt;Comparator&lt;/code&gt; interface&lt;/b&gt; requires         defining a the &lt;code&gt;compare()&lt;/code&gt; method.         This method is not defined in the classes that are being compared,         but usually in a small utility class which only defines this method.         Comparators are very useful for classes that can be sorted in multiple ways.     &lt;pre class="fragment"&gt;    if (&lt;i&gt;comparator&lt;/i&gt;.compare(x, y) &lt;&gt;         &lt;/pre&gt;&lt;/li&gt;&lt;/ul&gt;  &lt;h2&gt;Use predefined sorting and searching methods if possible.&lt;/h2&gt; &lt;p&gt;Java defines a number of searching and sorting methods.      You should always use these in preference to writing     your own because the library methods are almost always faster and have been well tested.    However, there are times that the predefined methods don't work    for your data structures, so it's also good to understand how these    algorithms work.    &lt;/p&gt;         &lt;h2&gt;Predefined sorting and searching methods for arrays&lt;/h2&gt; &lt;p&gt;See &lt;a href="http://javasort.blogspot.com/2009/11/array-library-methods-static-methods.html"&gt;Array Library Methods&lt;/a&gt; for a brief description of the static &lt;code&gt;Array.binarySearch()&lt;/code&gt; and &lt;code&gt;Array.sort()&lt;/code&gt; methods. &lt;/p&gt;   &lt;h2&gt;Predefined sorting and searching in the Collections classes&lt;/h2&gt; &lt;p&gt;See &lt;a href="http://javasort.blogspot.com/2009/11/collections-methods.html"&gt;Collections Class&lt;/a&gt;  for a brief description of the static &lt;code&gt;Collections.binarySearch()&lt;/code&gt; and &lt;code&gt;Collections.sort()&lt;/code&gt; methods.   This also has a brief discussion of data structures classes which are automatically sorted (those based on trees), or which have better than linear search  methods (based on trees or hashing). &lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-6753984746904437281?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/6753984746904437281/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/11/searching-and-sorting-overview.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/6753984746904437281'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/6753984746904437281'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/11/searching-and-sorting-overview.html' title='Searching and Sorting Overview'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-3073729634512635345</id><published>2009-11-30T12:15:00.001-08:00</published><updated>2009-11-30T12:15:34.448-08:00</updated><title type='text'>Algorithms: Recursive Binary Search</title><content type='html'>&lt;h2&gt;Recursive Binary Search&lt;/h2&gt; &lt;p&gt;Iterative algorithms, ie those with a loop, can usually be easily rewritten  to use recursive method calls instead of loops.   However the iterative version is usually simpler, faster, and uses less memory.   &lt;/p&gt;  &lt;p&gt;Some problems, eg traversing a tree, are better solved recursively because the recursive solution is so clear (eg, binary tree traversal). Iterative binary search is more efficient than the recursive form, but it is one of the  more plausible algorithms to use as an illustration of recursion. &lt;/p&gt;  &lt;p&gt;This recursive version checks to see if we're at the key (in which case it can return), otherwise it calls itself to solve a smaller problem, ie,  either the upper or lower half of the array. &lt;/p&gt;  &lt;h2&gt;Example&lt;/h2&gt; &lt;table summary="" border="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td valign="top"&gt;&lt;pre class="example2"&gt;  1&lt;br /&gt; 2&lt;br /&gt; 3&lt;br /&gt; 4&lt;br /&gt; 5&lt;br /&gt; 6&lt;br /&gt; 7&lt;br /&gt; 8&lt;br /&gt; 9&lt;br /&gt;10&lt;br /&gt;11&lt;br /&gt;12&lt;br /&gt;13&lt;br /&gt;14&lt;br /&gt;15&lt;br /&gt;16&lt;br /&gt;17&lt;br /&gt;18&lt;br /&gt;19&lt;br /&gt;20&lt;br /&gt;21&lt;br /&gt;22&lt;br /&gt;23&lt;br /&gt;24&lt;br /&gt;25&lt;br /&gt;26&lt;br /&gt;27&lt;br /&gt;28&lt;br /&gt;&lt;/pre&gt;&lt;/td&gt;&lt;td valign="top"&gt; &lt;div class="file"&gt;&lt;pre&gt;/** Recursive binary search of sorted array.    Negative value on failure.&lt;br /&gt;*  The upperbound index is not included in the search.&lt;br /&gt;*  This is to be consistent with the way Java in general expresses ranges.&lt;br /&gt;*  The performance is O(log N).&lt;br /&gt;*  @param sorted Array of sorted values to be searched.&lt;br /&gt;*  @param first Index of beginning of range.  First element is a[first].&lt;br /&gt;*  @param upto  Last element that is searched is sorted[upto-1].&lt;br /&gt;*  @param key   Value that is being looked for.&lt;br /&gt;*  @return      Returns index of the first match, or or -insertion_position&lt;br /&gt;*               -1 if key is not in the array. This value can easily be&lt;br /&gt;*               transformed into the position to insert it.&lt;br /&gt;*/&lt;br /&gt;public static int rBinarySearch(int[] sorted, int first, int upto, int key) {&lt;br /&gt;  &lt;br /&gt;   if (first &lt; upto) {&lt;br /&gt;       int mid = first + (upto - first) / 2;  // Compute mid point.&lt;br /&gt;       if (key &lt; sorted[mid]) {&lt;br /&gt;           return rBinarySearch(sorted, first, mid, key);&lt;br /&gt;          &lt;br /&gt;       } else if (key &gt; sorted[mid]) {&lt;br /&gt;           return rBinarySearch(sorted, mid+1, upto , key);&lt;br /&gt;          &lt;br /&gt;       } else {&lt;br /&gt;           return mid;   // Found it.&lt;br /&gt;       }&lt;br /&gt;   }&lt;br /&gt;   return -(first + 1);  // Failed to find key&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-3073729634512635345?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/3073729634512635345/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/11/algorithms-recursive-binary-search.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/3073729634512635345'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/3073729634512635345'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/11/algorithms-recursive-binary-search.html' title='Algorithms: Recursive Binary Search'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-1183636941546604811</id><published>2009-11-30T12:14:00.001-08:00</published><updated>2009-11-30T12:14:59.414-08:00</updated><title type='text'>Algorithms: Linear Search</title><content type='html'>&lt;h2&gt;Look at every element&lt;/h2&gt; This is a very straightforward loop comparing every element in the array with the key.  As soon as an equal value is found, it returns. If the loop finishes without finding a match, the search failed and -1 is returned.   &lt;h2&gt;Performance&lt;/h2&gt; For small arrays, linear search is a good solution because it's so straightforward. In an array of a million elements linear search on average will take 500,000 comparisons to find the key. For a &lt;i&gt;much&lt;/i&gt; faster search, take a look at  &lt;a href="http://leepoint.net/notes-java/algorithms/searching/binarysearch.html"&gt;binary search&lt;/a&gt;.  &lt;h2&gt;Example&lt;/h2&gt; &lt;table summary="" border="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td valign="top"&gt;&lt;pre class="example2"&gt;  1&lt;br /&gt; 2&lt;br /&gt; 3&lt;br /&gt; 4&lt;br /&gt; 5&lt;br /&gt; 6&lt;br /&gt; 7&lt;br /&gt; 8&lt;br /&gt; 9&lt;br /&gt;10&lt;br /&gt;11&lt;br /&gt;12&lt;br /&gt;13&lt;br /&gt;14&lt;br /&gt;15&lt;br /&gt;16&lt;br /&gt;17&lt;br /&gt;18&lt;br /&gt;19&lt;br /&gt;20&lt;br /&gt;&lt;/pre&gt;&lt;/td&gt;&lt;td valign="top"&gt; &lt;div class="file"&gt;&lt;pre&gt;/** Linear search of array for key.  Returns index or -1 if not found.&lt;br /&gt;*  The upperbound index is not included in the search.&lt;br /&gt;*  This is to be consistent with the way Java in general expresses ranges.&lt;br /&gt;*  This searches from low to high index values.&lt;br /&gt;*  The performance is O(N).&lt;br /&gt;*  @param a Array of values to be searched.&lt;br /&gt;*  @param first Index of beginning of range.  First element is a[first].&lt;br /&gt;*  @param upto  Last element that is searched is a[upto-1].&lt;br /&gt;*  @param key   Value that is being looked for.&lt;br /&gt;*  @return      Returns index of the first match, or -1 if no match.&lt;br /&gt;*/&lt;br /&gt;public static int linearSearch(int[] a, int first, int upto, int key) {&lt;br /&gt;  &lt;br /&gt;   for (int i = first; i &lt; upto; i++) {&lt;br /&gt;       if (key == a[i]) {&lt;br /&gt;           return i;  // Found key, return index.&lt;br /&gt;       }&lt;br /&gt;   }&lt;br /&gt;   return -1;        // Failed to find key&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-1183636941546604811?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/1183636941546604811/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/11/algorithms-linear-search.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/1183636941546604811'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/1183636941546604811'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/11/algorithms-linear-search.html' title='Algorithms: Linear Search'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-8473268275718968760</id><published>2009-11-30T12:13:00.000-08:00</published><updated>2009-11-30T12:14:39.534-08:00</updated><title type='text'>Algorithms: Binary Search</title><content type='html'>&lt;h2&gt;Divide in half&lt;/h2&gt; &lt;p&gt;A fast way to search a sorted array is to use a &lt;i&gt;binary search&lt;/i&gt;. The idea is to look at the element in the middle.   If the key is equal to that, the search is finished. If the key is less than the middle element, do a binary search on the first half.   If it's greater, do a binary search of the second half. &lt;/p&gt;  &lt;h2&gt;Performance&lt;/h2&gt; &lt;p&gt;The advantage of a binary search over a linear search is astounding for large numbers.  For an array of a million elements, binary search, O(log N),  will find the target element with a worst case of only 20 comparisons.  Linear search, O(N), on average will take 500,000 comparisons to find the element. Probably the only faster kind of search uses &lt;i&gt;hashing&lt;/i&gt;, a topic that isn't covered in these notes. &lt;/p&gt;  &lt;p&gt;This performance comes at a price - the array must be sorted first. Because sorting isn't a fast operation, O(N log N), it may not be worth the effort to sort when there are only a few searches. &lt;/p&gt;  &lt;h2&gt;Example&lt;/h2&gt; &lt;table summary="" border="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td valign="top"&gt;&lt;pre class="example2"&gt;  1&lt;br /&gt; 2&lt;br /&gt; 3&lt;br /&gt; 4&lt;br /&gt; 5&lt;br /&gt; 6&lt;br /&gt; 7&lt;br /&gt; 8&lt;br /&gt; 9&lt;br /&gt;10&lt;br /&gt;11&lt;br /&gt;12&lt;br /&gt;13&lt;br /&gt;14&lt;br /&gt;15&lt;br /&gt;16&lt;br /&gt;17&lt;br /&gt;18&lt;br /&gt;19&lt;br /&gt;20&lt;br /&gt;21&lt;br /&gt;22&lt;br /&gt;23&lt;br /&gt;24&lt;br /&gt;25&lt;br /&gt;26&lt;br /&gt;27&lt;br /&gt;&lt;/pre&gt;&lt;/td&gt;&lt;td valign="top"&gt; &lt;div class="file"&gt;&lt;pre&gt;//=========================================================== binarySearch&lt;br /&gt;/** Binary search of sorted array.  Negative value on search failure.&lt;br /&gt;*  The upperbound index is not included in the search.&lt;br /&gt;*  This is to be consistent with the way Java in general expresses ranges.&lt;br /&gt;*  The performance is O(log N).&lt;br /&gt;*  @param sorted Array of sorted values to be searched.&lt;br /&gt;*  @param first Index of first element to serach, sorted[first].&lt;br /&gt;*  @param upto  Index of last element to search, sorted[upto-1].&lt;br /&gt;*  @param key   Value that is being looked for.&lt;br /&gt;*  @return      Returns index of the first match, or or -insertion_position&lt;br /&gt;*               -1 if key is not in the array. This value can easily be&lt;br /&gt;*               transformed into the position to insert it.&lt;br /&gt;*/&lt;br /&gt;public static int binarySearch(int[] sorted, int first, int upto, int key) {&lt;br /&gt;  &lt;br /&gt;   while (first &lt; upto) {&lt;br /&gt;       int mid = (first + upto) / 2;  // Compute mid point.&lt;br /&gt;       if (key &lt; sorted[mid]) {&lt;br /&gt;           upto = mid;     // repeat search in bottom half.&lt;br /&gt;       } else if (key &gt; sorted[mid]) {&lt;br /&gt;           first = mid + 1;  // Repeat search in top half.&lt;br /&gt;       } else {&lt;br /&gt;           return mid;     // Found it. return position&lt;br /&gt;       }&lt;br /&gt;   }&lt;br /&gt;   return -(first + 1);    // Failed to find key&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt; &lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;   &lt;p&gt;&lt;b&gt;Style violation?&lt;/b&gt; Note: this code violates the advice of not altering method parameters. The reason is that it can under some circumstances make the code less readable.  In this case, however, the code would probably be less readable by introducing two extra local variables. &lt;/p&gt;   &lt;h2&gt;Computing the midpoint&lt;/h2&gt; &lt;p&gt;There are two common ways to compute the index of the middle element. The most common way is to add the lowest and hightest and divide by two. For example, &lt;/p&gt; &lt;pre class="fragment"&gt;int mid = (first + last) + 2;&lt;/pre&gt;  &lt;p&gt;&lt;b&gt;Overflow&lt;/b&gt;.  This works well, or at least has worked well, until recently. The problem appeared when memories, and arrays, got very large. For the first time the sum of two array indexes, an intermediate value in the computation, can overflow the size of an int.  Computing the midpoint by adding the two and then dividing  doesn't work. &lt;/p&gt;  &lt;p&gt;&lt;b&gt;Reordering the expession avoids overflow.&lt;/b&gt;  The solution is to  rewrite the expression so that no intermediate value overflows the size of an int.  This is easy to do using the following. &lt;/p&gt; &lt;pre class="fragment"&gt;int mid = first + (last - first) / 2;&lt;/pre&gt;  &lt;p&gt;For most programs the difference between the two computations will  never be seen because it will only appeaer with very large arrays. &lt;/p&gt;   &lt;h2&gt;Variation on binary search&lt;/h2&gt; &lt;p&gt;The following method shows another version of a binary search method: (1) it compares elements of a string array (so comparisons use the &lt;code&gt;compareTo()&lt;/code&gt; method), and (2) it sorts the entire array so fewer parameters are supplied, and therefore local variables are declared to take their place. &lt;/p&gt;  &lt;table summary="" border="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td valign="top"&gt;&lt;pre class="example2"&gt;  1&lt;br /&gt; 2&lt;br /&gt; 3&lt;br /&gt; 4&lt;br /&gt; 5&lt;br /&gt; 6&lt;br /&gt; 7&lt;br /&gt; 8&lt;br /&gt; 9&lt;br /&gt;10&lt;br /&gt;11&lt;br /&gt;12&lt;br /&gt;13&lt;br /&gt;14&lt;br /&gt;15&lt;br /&gt;16&lt;br /&gt;&lt;/pre&gt;&lt;/td&gt;&lt;td valign="top"&gt; &lt;div class="file"&gt;&lt;pre&gt;public static int binarySearch(String[] sorted, String key) {&lt;br /&gt;   int first = 0;&lt;br /&gt;   int upto  = sorted.length;&lt;br /&gt;  &lt;br /&gt;   while (first &lt; upto) {&lt;br /&gt;       int mid = (first + upto) / 2;  // Compute mid point.&lt;br /&gt;       if (key.compareTo(sorted[mid]) &lt; 0) {&lt;br /&gt;           upto = mid;       // repeat search in bottom half.&lt;br /&gt;       } else if (key.compareTo(sorted[mid]) &gt; 0) {&lt;br /&gt;           first = mid + 1;  // Repeat search in top half.&lt;br /&gt;       } else {&lt;br /&gt;           return mid;       // Found it. return position&lt;br /&gt;       }&lt;br /&gt;   }&lt;br /&gt;   return -(first + 1);      // Failed to find key&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-8473268275718968760?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/8473268275718968760/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/11/algorithms-binary-search.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/8473268275718968760'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/8473268275718968760'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/11/algorithms-binary-search.html' title='Algorithms: Binary Search'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-78641573690670126</id><published>2009-11-30T11:31:00.000-08:00</published><updated>2009-11-30T11:40:11.465-08:00</updated><title type='text'>Sorting Effectively in Java</title><content type='html'>&lt;span id="lblBody"&gt;This tutorial is generally about sorting in Java – ways to do it, and how to do it correctly, quickly, and effectively. This tutorial will use one problem, and shows the many approaches to do so.&lt;br /&gt;&lt;br /&gt;Here’s the problem:&lt;br /&gt;Suppose you’re to sort a list of books, given by the number of pages, and the initial of the author. The style of input is on one line, a number between 0 – 999 denoting the number of pages, a space, then the author’s initials with 2 uppercase letters.&lt;br /&gt;&lt;br /&gt;We are to sort them by the number of pages, and then by the first, then last initials of the author.&lt;br /&gt;&lt;br /&gt;The input will be given by one string, with one number denoting the number of books. We’re to implement a “bookOrder” method that returns the sorted string.&lt;br /&gt;&lt;br /&gt;Input:&lt;br /&gt;15 AB 219 AE 518 SE 518 AB 17 CE, 5&lt;br /&gt;&lt;br /&gt;Output:&lt;br /&gt;15 AB 17 CE 219 AE 518 AB 518 SE&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size:100%;"&gt;Method 1&lt;/span&gt;&lt;br /&gt;Because in competitions, this is timed, so one might write it very inefficently, using bubblesort:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;table width="100%" cellspacing="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class="codebg"&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;import java.util.*;&lt;br /&gt;&lt;span class="cs"&gt;public &lt;/span&gt;&lt;span class="cs"&gt;class&lt;/span&gt; Book{&lt;br /&gt;   &lt;span class="cs"&gt;public &lt;/span&gt;&lt;span class="cs"&gt;String&lt;/span&gt; bookOrder( &lt;span class="cs"&gt;String&lt;/span&gt; books, &lt;span class="cs"&gt;int&lt;/span&gt; number ){&lt;br /&gt;      &lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;int[] pages = &lt;span class="cs"&gt;new &lt;/span&gt;int[ number ];&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;String[] title = &lt;span class="cs"&gt;new &lt;/span&gt;String[ number ];&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;StringTokenizer st = &lt;span class="cs"&gt;new &lt;/span&gt;StringTokenizer( books );&lt;br /&gt;&lt;br /&gt;   &lt;span class="comment"&gt;// Parsing&lt;/span&gt;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;for&lt;/span&gt; ( &lt;span class="cs"&gt;int&lt;/span&gt; i = 0; i &lt; number; i++ ){&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;pages[i] = Integer.parseInt( st.nextToken() );&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;title[i] = st.nextToken();&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;&lt;br /&gt;   &lt;span class="comment"&gt;// Bubblesort&lt;/span&gt;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;for&lt;/span&gt; ( &lt;span class="cs"&gt;int&lt;/span&gt; i = 0; i &lt; number; i++ ){&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;for&lt;/span&gt; ( &lt;span class="cs"&gt;int&lt;/span&gt; j = 0; j &lt; number - 1; j++ ){&lt;br /&gt;       &lt;span class="comment"&gt;// This does the actual comparison&lt;/span&gt;&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;if&lt;/span&gt; ( pages[j] &gt; pages[j+1] ||&lt;br /&gt;           &lt;span class="cs"&gt;&lt;/span&gt;( pages[j] == pages[j+1] &amp;amp;&amp;amp; title[j].compareTo( title[j+1] ) &gt; 0 ) ){&lt;br /&gt;           &lt;span class="comment"&gt;// Swapping&lt;/span&gt;&lt;br /&gt;           &lt;span class="cs"&gt;&lt;/span&gt;pages[j] ^= pages[j+1];&lt;br /&gt;           &lt;span class="cs"&gt;&lt;/span&gt;pages[j+1] ^= pages[j];&lt;br /&gt;           &lt;span class="cs"&gt;&lt;/span&gt;pages[j] ^= pages[j+1];&lt;br /&gt;           &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;String&lt;/span&gt; temp = title[j];&lt;br /&gt;           &lt;span class="cs"&gt;&lt;/span&gt;title[j] = title[j+1];&lt;br /&gt;           &lt;span class="cs"&gt;&lt;/span&gt;title[j+1] = temp;&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;&lt;br /&gt;   &lt;span class="comment"&gt;// Returns it in the format required.    &lt;/span&gt;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;String&lt;/span&gt; s = "";&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;for&lt;/span&gt; ( &lt;span class="cs"&gt;int&lt;/span&gt; i = 0; i &lt; number; i++ ){&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;s += (int)pages[i] + " " + title[i] + " ";&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;   &lt;span class="comment"&gt;// trim() trims the trailing ( and leading spaces ) in a string.&lt;/span&gt;&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;return&lt;/span&gt; s.trim();&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The above method took about 5 minutes to write, is stable, but isn't very efficient. ( At O( n^2 ) )&lt;br /&gt;&lt;br /&gt;This code is also very flexible, as you only need to change this statement to sort it differently:&lt;br /&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;table width="100%" cellspacing="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class="codebg"&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;if ( pages[j] &gt; pages[j+1] ||&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;( pages[j] == pages[j+1] &amp;amp;&amp;amp; title[j].compareTo( title[j+1] ) &gt; 0 ) )&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;If we wanted to sort by initial first and then page number, we can easily modified this to:&lt;br /&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;table width="100%" cellspacing="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class="codebg"&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;if ( title[j].compareTo( title[j+1] ) &gt; 0 ) ||&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;( title[j].compareTo( title[j+1] ) == 0 &amp;amp;&amp;amp; pages[j] &gt; pages[j+1] ) )&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;or changed the signs if we wanted to sort descendingly:&lt;br /&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;table width="100%" cellspacing="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class="codebg"&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;if ( pages[j] &lt; pages[j+1] ||&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;( pages[j] == pages[j+1] &amp;amp;&amp;amp; title[j].compareTo( title[j+1] ) &gt; 0 ) )&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size:100%;"&gt;Method 2&lt;/span&gt;&lt;br /&gt;A better and more efficient way is to use the Java API. This is using a relatively underused class java.util.Arrays and the interface Comparable:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;table width="100%" cellspacing="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class="codebg"&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;import java.util.*;&lt;br /&gt;&lt;span class="cs"&gt;public &lt;/span&gt;&lt;span class="cs"&gt;class&lt;/span&gt; Book{&lt;br /&gt;   &lt;span class="cs"&gt;private &lt;/span&gt;&lt;span class="cs"&gt;class&lt;/span&gt; B &lt;span class="cs"&gt;implements&lt;/span&gt; Comparable {&lt;br /&gt;   &lt;span class="comment"&gt;// Fields to be sorted&lt;/span&gt;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;int&lt;/span&gt; pages;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;String&lt;/span&gt; title;&lt;br /&gt;  &lt;br /&gt;   &lt;span class="comment"&gt;// Initializer&lt;/span&gt;&lt;br /&gt;   &lt;span class="cs"&gt;public &lt;/span&gt;B ( &lt;span class="cs"&gt;int&lt;/span&gt; p, &lt;span class="cs"&gt;String&lt;/span&gt; t ){&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;title = t;&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;pages = p;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;  &lt;br /&gt;   &lt;span class="comment"&gt;// The required compareTo method.&lt;/span&gt;&lt;br /&gt;   &lt;span class="cs"&gt;public &lt;/span&gt;&lt;span class="cs"&gt;int&lt;/span&gt; compareTo( &lt;span class="cs"&gt;Object&lt;/span&gt; o ){&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;B k = (B) o;&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;if&lt;/span&gt; ( pages != k.pages ){&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;return&lt;/span&gt; pages - k.pages;&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;else&lt;/span&gt;&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;return&lt;/span&gt; title.compareTo( k.title );&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;&lt;br /&gt;   &lt;span class="cs"&gt;public &lt;/span&gt;&lt;span class="cs"&gt;String&lt;/span&gt; bookOrder( &lt;span class="cs"&gt;String&lt;/span&gt; books, &lt;span class="cs"&gt;int&lt;/span&gt; number ){&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;B[] book = &lt;span class="cs"&gt;new &lt;/span&gt;B[ number ];&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;StringTokenizer st = &lt;span class="cs"&gt;new &lt;/span&gt;StringTokenizer( books );&lt;br /&gt;&lt;br /&gt;   &lt;span class="comment"&gt;// Parsing&lt;/span&gt;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;for&lt;/span&gt; ( &lt;span class="cs"&gt;int&lt;/span&gt; i = 0; i &lt; number; i++ ){&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;book[i] = &lt;span class="cs"&gt;new &lt;/span&gt;B(Integer.parseInt( st.nextToken() ), st.nextToken() );&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;  &lt;br /&gt;   &lt;span class="comment"&gt;// Using Arrays.sort&lt;/span&gt;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;Arrays.sort( book );&lt;br /&gt;  &lt;br /&gt;   &lt;span class="comment"&gt;// Return it in the format required.&lt;/span&gt;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;String&lt;/span&gt; s = "";&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;for&lt;/span&gt; ( &lt;span class="cs"&gt;int&lt;/span&gt; i = 0; i &lt; number; i++ ){&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;s += (int)book[i].pages + " " + book[i].title + " ";&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;return&lt;/span&gt; s.trim();&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This ensures that it runs in O( n * log n ) time, using a tuned quicksort.  The best thing about writing&lt;br /&gt;the code this way is that it's cleaner, and it's also less error-prone, if you let the API do the work.&lt;br /&gt;&lt;br /&gt;Let's go over it in detail:&lt;br /&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;table width="100%" cellspacing="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class="codebg"&gt;&lt;pre&gt;&lt;span class="cs"&gt;private &lt;/span&gt;&lt;span class="cs"&gt;class&lt;/span&gt; B &lt;span class="cs"&gt;implements&lt;/span&gt; Comparable&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This is a private helper class.  It implements Comparable so that we can sort it later.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;table width="100%" cellspacing="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class="codebg"&gt;&lt;pre&gt;&lt;span class="cs"&gt;public &lt;/span&gt;&lt;span class="cs"&gt;int&lt;/span&gt; compareTo( &lt;span class="cs"&gt;Object&lt;/span&gt; o ){&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;B k = (B) o;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;if&lt;/span&gt; ( pages != k.pages ){&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;return&lt;/span&gt; pages - k.pages;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;else&lt;/span&gt;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;return&lt;/span&gt; title.compareTo( k.title );&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This method is the method that does the comparing. Naturally, it returns a negative integer if this object is smaller, a zero if they're the same, and a positive interger if the specified Object is smaller.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;table width="100%" cellspacing="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class="codebg"&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;Arrays.sort( Object[] )&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This lets us sort anything, but it requires that all elements in the array be implementing the Comparable interface. That means if you're sorting just ints, or doubles, or Strings, this is very handy and let you get the work done quicker. Why reinvent the wheel, after all?&lt;br /&gt;&lt;br /&gt;The above way is not that hard to implement, and it doesn't take too long, but generally requires me to remember too much syntax.&lt;br /&gt;&lt;br /&gt;However, it is the preferable way to sort things in Java.  Learning it helps a lot in sorting in general.&lt;br /&gt;&lt;br /&gt;To modify what to sort, we simply modify the compareTo method:&lt;br /&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;table width="100%" cellspacing="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class="codebg"&gt;&lt;pre&gt;&lt;span class="cs"&gt;public &lt;/span&gt;&lt;span class="cs"&gt;int&lt;/span&gt; compareTo( &lt;span class="cs"&gt;Object&lt;/span&gt; o ){&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;B k = (B) o;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;if&lt;/span&gt; ( pages != k.pages ){&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;return&lt;/span&gt; pages - k.pages;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;else&lt;/span&gt;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;return&lt;/span&gt; title.compareTo( k.title );&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;as with method 1, if we wanted to sort descendingly:&lt;br /&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;table width="100%" cellspacing="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class="codebg"&gt;&lt;pre&gt;&lt;span class="cs"&gt;public &lt;/span&gt;&lt;span class="cs"&gt;int&lt;/span&gt; compareTo( &lt;span class="cs"&gt;Object&lt;/span&gt; o ){&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;B k = (B) o;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;if&lt;/span&gt; ( pages != k.pages ){&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;return&lt;/span&gt; k.pages - pages;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;else&lt;/span&gt;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;return&lt;/span&gt; title.compareTo( k.title );&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;or title first:&lt;br /&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;table width="100%" cellspacing="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class="codebg"&gt;&lt;pre&gt;&lt;span class="cs"&gt;public &lt;/span&gt;&lt;span class="cs"&gt;int&lt;/span&gt; compareTo( &lt;span class="cs"&gt;Object&lt;/span&gt; o ){&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;B k = (B) o;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;if&lt;/span&gt; ( title.compareTo( k.title ) != 0 )&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;return&lt;/span&gt; title.compareTo( k.title );&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;else&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;return&lt;/span&gt; pages - k.pages;&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;or title descendingly:&lt;br /&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;table width="100%" cellspacing="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class="codebg"&gt;&lt;pre&gt;&lt;span class="cs"&gt;public &lt;/span&gt;&lt;span class="cs"&gt;int&lt;/span&gt; compareTo( &lt;span class="cs"&gt;Object&lt;/span&gt; o ){&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;B k = (B) o;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;if&lt;/span&gt; ( title.compareTo( k.title ) != 0 )&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;return&lt;/span&gt; -1 * title.compareTo( k.title );&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;else&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;return&lt;/span&gt; pages - k.pages;&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size:100%;"&gt;Method 3&lt;/span&gt;&lt;br /&gt;So is there another alternative?&lt;br /&gt;&lt;br /&gt;This requires us to think about the boundry conditions. Since Arrays.sort also sort Strings, we can format the entire thing as an Array of Strings, and then sort them:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;table width="100%" cellspacing="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class="codebg"&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;import java.util.*;&lt;br /&gt;&lt;span class="cs"&gt;public &lt;/span&gt;&lt;span class="cs"&gt;class&lt;/span&gt; Book{&lt;br /&gt;   &lt;span class="cs"&gt;public &lt;/span&gt;&lt;span class="cs"&gt;String&lt;/span&gt; bookOrder( &lt;span class="cs"&gt;String&lt;/span&gt; books, &lt;span class="cs"&gt;int&lt;/span&gt; number ){&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;StringTokenizer st = &lt;span class="cs"&gt;new &lt;/span&gt;StringTokenizer( books );&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;String[] book = &lt;span class="cs"&gt;new &lt;/span&gt;String[ number ];&lt;br /&gt;&lt;br /&gt;   &lt;span class="comment"&gt;// Parsing&lt;/span&gt;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;for&lt;/span&gt; ( &lt;span class="cs"&gt;int&lt;/span&gt; i = 0; i &lt; number; i++ ){&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;int&lt;/span&gt; pages = Integer.parseInt( st.nextToken() );&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;String&lt;/span&gt; title = st.nextToken();&lt;br /&gt;&lt;br /&gt;&lt;span class="comment"&gt;        /** Format is as following:&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span class="comment"&gt;         * DDDTTNNNNN&lt;/span&gt;&lt;br /&gt;&lt;span class="comment"&gt;         * Where DDD is the number of pages&lt;/span&gt;&lt;br /&gt;&lt;span class="comment"&gt;         * TT is the initials&lt;/span&gt;&lt;br /&gt;&lt;span class="comment"&gt;         * and NNNNN is the original string&lt;/span&gt;&lt;br /&gt;&lt;span class="comment"&gt;         **/&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;book[i] = format( pages ) + title + pages + " " + title;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;  &lt;br /&gt;   &lt;span class="comment"&gt;// Using Arrays.sort&lt;/span&gt;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;Arrays.sort( book );&lt;br /&gt;  &lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;String&lt;/span&gt; s = "";&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;for&lt;/span&gt; ( &lt;span class="cs"&gt;int&lt;/span&gt; i = 0; i &lt; number; i++ ){&lt;br /&gt;   &lt;span class="comment"&gt;// Why 5?  the first 5 characters are throw away letters to be sorted&lt;/span&gt;&lt;br /&gt;       &lt;span class="cs"&gt;&lt;/span&gt;s += book[i].substring(5) + " ";&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;return&lt;/span&gt; s.trim();&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;&lt;br /&gt;   &lt;span class="comment"&gt;// This pads the number of pages with zeros.&lt;/span&gt;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;String&lt;/span&gt; format ( &lt;span class="cs"&gt;int&lt;/span&gt; pages ){&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;String&lt;/span&gt; temp = "0000000" + pages;&lt;br /&gt;   &lt;span class="comment"&gt;// Why 3?  Since it only goes up to 999, we only need the last 3 digits.&lt;/span&gt;&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;&lt;span class="cs"&gt;return&lt;/span&gt; temp.substring( temp.length() - 3 );&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The above works, is very short to write, and is pretty intuitive. In general, I recommend the second method, but usually I have to look up the syntax on an API, and the above saves me some time, and time is a very important constraint sometimes.&lt;br /&gt;&lt;br /&gt;To modify what to sort, we simply modify the parsing line:&lt;br /&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;table width="100%" cellspacing="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class="codebg"&gt;&lt;pre&gt;   &lt;span class="cs"&gt;&lt;/span&gt;book[i] = format( pages ) + title + pages + " " + title;&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;to descending pages:&lt;br /&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;table width="100%" cellspacing="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class="codebg"&gt;&lt;pre&gt;   &lt;span class="cs"&gt;&lt;/span&gt;book[i] = format( 999 - pages ) + title + pages + " " + title;&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;to initials:&lt;br /&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;table width="100%" cellspacing="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class="codebg"&gt;&lt;pre&gt;   &lt;span class="cs"&gt;&lt;/span&gt;book[i] = title + format( 999 - pages ) + pages + " " + title;&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;to descending initials:&lt;br /&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;table width="100%" cellspacing="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class="codebg"&gt;&lt;pre&gt;   &lt;span class="cs"&gt;&lt;/span&gt;book[i] = (char) ('Z' - ( title.charAt(0) - 'A' )) + (char) ('Z' - ( title.charAt(1) - 'A' ) +&lt;br /&gt;     &lt;span class="cs"&gt;&lt;/span&gt;format( 999 - pages ) + pages + " " + title;&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;To test the above methods, we just need to add the main method:&lt;br /&gt;&lt;pre&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;table width="100%" cellspacing="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class="codebg"&gt;&lt;pre&gt;    &lt;span class="cs"&gt;public static &lt;/span&gt;&lt;span class="cs"&gt;void&lt;/span&gt; main( String[] args )&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;{&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;Book a = &lt;span class="cs"&gt;new &lt;/span&gt;Book();&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;System.out.println( a.bookOrder( "15 AB 219 AE 518 SE 518 AB 17 CE", 5 ) );&lt;br /&gt;   &lt;span class="cs"&gt;&lt;/span&gt;}&lt;br /&gt;&lt;span class="cs"&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This was meant to be a quick tutorial to coders that already knows how to program, and to provide them alternative way of solving a problem quicker.&lt;br /&gt;&lt;span style="font-size:78%;"&gt;http://devhood.com/Tutorials/tutorial_details.aspx?tutorial_id=395&lt;/span&gt;&lt;br /&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-78641573690670126?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/78641573690670126/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/11/sorting-effectively-in-java.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/78641573690670126'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/78641573690670126'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/11/sorting-effectively-in-java.html' title='Sorting Effectively in Java'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-3864400416472445553</id><published>2009-11-30T11:26:00.000-08:00</published><updated>2009-11-30T11:27:35.665-08:00</updated><title type='text'>Sorting Objects</title><content type='html'>&lt;p&gt;For simplicity we've applied the sorting algorithms we've looked at thus far to a primitive data type: &lt;tt&gt;long&lt;/tt&gt;. However, sorting routines will more likely be applied to objects than primitive types. Accordingly, we show a Java program in Listing 3.4, &lt;tt&gt;objectSort.java&lt;/tt&gt;, that sorts an array of &lt;tt&gt;Person&lt;/tt&gt; objects (last seen in the &lt;tt&gt;classDataArray.java&lt;/tt&gt; program in Chapter 2).&lt;/p&gt; &lt;h3&gt;Java Code for Sorting Objects&lt;/h3&gt; &lt;p&gt;The algorithm used in our Java program is the insertion sort from the preceding section. The &lt;tt&gt;Person&lt;/tt&gt; objects are sorted on &lt;tt&gt;lastName&lt;/tt&gt;; this is the key field. The &lt;tt&gt;objectSort.java&lt;/tt&gt; program is shown in Listing 3.4.&lt;/p&gt; &lt;h4&gt;LISTING 3.4 The &lt;tt&gt;objectSort.java&lt;/tt&gt; Program&lt;/h4&gt; &lt;pre&gt;// objectSort.java&lt;br /&gt;// demonstrates sorting objects (uses insertion sort)&lt;br /&gt;// to run this program: C&gt;java ObjectSortApp&lt;br /&gt;////////////////////////////////////////////////////////////////&lt;br /&gt;class Person&lt;br /&gt;{&lt;br /&gt;private String lastName;&lt;br /&gt;private String firstName;&lt;br /&gt;private int age;&lt;br /&gt;//-----------------------------------------------------------&lt;br /&gt;public Person(String last, String first, int a)&lt;br /&gt; {                // constructor&lt;br /&gt; lastName = last;&lt;br /&gt; firstName = first;&lt;br /&gt; age = a;&lt;br /&gt; }&lt;br /&gt;//-----------------------------------------------------------&lt;br /&gt;public void displayPerson()&lt;br /&gt; {&lt;br /&gt; System.out.print("  Last name: " + lastName);&lt;br /&gt; System.out.print(", First name: " + firstName);&lt;br /&gt; System.out.println(", Age: " + age);&lt;br /&gt; }&lt;br /&gt;//-----------------------------------------------------------&lt;br /&gt;public String getLast()      // get last name&lt;br /&gt; { return lastName; }&lt;br /&gt;} // end class Person&lt;br /&gt;////////////////////////////////////////////////////////////////&lt;br /&gt;class ArrayInOb&lt;br /&gt;{&lt;br /&gt;private Person[] a;        // ref to array a&lt;br /&gt;private int nElems;        // number of data items&lt;br /&gt;//--------------------------------------------------------------&lt;br /&gt;public ArrayInOb(int max)     // constructor&lt;br /&gt; {&lt;br /&gt; a = new Person[max];        // create the array&lt;br /&gt; nElems = 0;            // no items yet&lt;br /&gt; }&lt;br /&gt;//--------------------------------------------------------------&lt;br /&gt;                 // put person into array&lt;br /&gt;public void insert(String last, String first, int age)&lt;br /&gt; {&lt;br /&gt; a[nElems] = new Person(last, first, age);&lt;br /&gt; nElems++;             // increment size&lt;br /&gt; }&lt;br /&gt;//--------------------------------------------------------------&lt;br /&gt;public void display()       // displays array contents&lt;br /&gt; {&lt;br /&gt; for(int j=0; j&lt;nelems; for="" each="" display="" it="" public="" void="" int="" out="1;"&gt;&lt;nelems; is="" dividing="" line="" temp="a[out];" remove="" marked="" person="" start="" shifting="" at="" out="" in="out;"&gt;0 &amp;amp;&amp;amp;        // until smaller one found,&lt;br /&gt;      a[in-1].getLast().compareTo(temp.getLast())&gt;0)&lt;br /&gt;    {&lt;br /&gt;    a[in] = a[in-1];     // shift item to the right&lt;br /&gt;    --in;          // go left one position&lt;br /&gt;    }&lt;br /&gt;   a[in] = temp;        // insert marked item&lt;br /&gt;   } // end for&lt;br /&gt; } // end insertionSort()&lt;br /&gt;//--------------------------------------------------------------&lt;br /&gt;} // end class ArrayInOb&lt;br /&gt;////////////////////////////////////////////////////////////////&lt;br /&gt;class ObjectSortApp&lt;br /&gt;{&lt;br /&gt;public static void main(String[] args)&lt;br /&gt; {&lt;br /&gt; int maxSize = 100;       // array size&lt;br /&gt; ArrayInOb arr;         // reference to array&lt;br /&gt; arr = new ArrayInOb(maxSize); // create the array&lt;br /&gt;&lt;br /&gt; arr.insert("Evans", "Patty", 24);&lt;br /&gt; arr.insert("Smith", "Doc", 59);&lt;br /&gt; arr.insert("Smith", "Lorraine", 37);&lt;br /&gt; arr.insert("Smith", "Paul", 37);&lt;br /&gt; arr.insert("Yee", "Tom", 43);&lt;br /&gt; arr.insert("Hashimoto", "Sato", 21);&lt;br /&gt; arr.insert("Stimson", "Henry", 29);&lt;br /&gt; arr.insert("Velasquez", "Jose", 72);&lt;br /&gt; arr.insert("Vang", "Minh", 22);&lt;br /&gt; arr.insert("Creswell", "Lucinda", 18);&lt;br /&gt;&lt;br /&gt; System.out.println("Before sorting:");&lt;br /&gt; arr.display();         // display items&lt;br /&gt;&lt;br /&gt; arr.insertionSort();      // insertion-sort them&lt;br /&gt;&lt;br /&gt; System.out.println("After sorting:");&lt;br /&gt; arr.display();         // display them again&lt;br /&gt; } // end main()&lt;br /&gt;} // end class ObjectSortApp&lt;br /&gt;////////////////////////////////////////////////////////////////&lt;/nelems;&gt;&lt;/nelems;&gt;&lt;/pre&gt; &lt;p&gt;Here's the output of this program:&lt;/p&gt; &lt;pre&gt;Before sorting:&lt;br /&gt;Last name: Evans, First name: Patty, Age: 24&lt;br /&gt;Last name: Smith, First name: Doc, Age: 59&lt;br /&gt;Last name: Smith, First name: Lorraine, Age: 37&lt;br /&gt;Last name: Smith, First name: Paul, Age: 37&lt;br /&gt;Last name: Yee, First name: Tom, Age: 43&lt;br /&gt;Last name: Hashimoto, First name: Sato, Age: 21&lt;br /&gt;Last name: Stimson, First name: Henry, Age: 29&lt;br /&gt;Last name: Velasquez, First name: Jose, Age: 72&lt;br /&gt;Last name: Vang, First name: Minh, Age: 22&lt;br /&gt;Last name: Creswell, First name: Lucinda, Age: 18&lt;br /&gt;&lt;br /&gt;After sorting:&lt;br /&gt;Last name: Creswell, First name: Lucinda, Age: 18&lt;br /&gt;Last name: Evans, First name: Patty, Age: 24&lt;br /&gt;Last name: Hashimoto, First name: Sato, Age: 21&lt;br /&gt;Last name: Smith, First name: Doc, Age: 59&lt;br /&gt;Last name: Smith, First name: Lorraine, Age: 37&lt;br /&gt;Last name: Smith, First name: Paul, Age: 37&lt;br /&gt;Last name: Stimson, First name: Henry, Age: 29&lt;br /&gt;Last name: Vang, First name: Minh, Age: 22&lt;br /&gt;Last name: Velasquez, First name: Jose, Age: 72&lt;br /&gt;Last name: Yee, First name: Tom, Age: 43&lt;/pre&gt; &lt;h3&gt;Lexicographical Comparisons&lt;/h3&gt; &lt;p&gt;The &lt;tt&gt;insertSort()&lt;/tt&gt; method in &lt;tt&gt;objectSort.java&lt;/tt&gt; is similar to that in &lt;tt&gt;insertSort.java&lt;/tt&gt;, but it has been adapted to compare the &lt;tt&gt;lastName&lt;/tt&gt; key values of records rather than the value of a primitive type.&lt;/p&gt; &lt;p&gt;We use the &lt;tt&gt;compareTo()&lt;/tt&gt; method of the &lt;tt&gt;String&lt;/tt&gt; class to perform the comparisons in the &lt;tt&gt;insertSort()&lt;/tt&gt; method. Here's the expression that uses it:&lt;/p&gt; &lt;pre&gt;a[in-1].getLast().compareTo(temp.getLast()) &gt; 0&lt;/pre&gt; &lt;p&gt;The &lt;tt&gt;compareTo()&lt;/tt&gt; method returns different integer values depending on the lexicographical (that is, alphabetical) ordering of the &lt;tt&gt;String&lt;/tt&gt; for which it's invoked and the &lt;tt&gt;String&lt;/tt&gt; passed to it as an argument, as shown in Table 3.1.&lt;/p&gt; &lt;h4&gt;&lt;b&gt;TABLE 3.1 Operation of the &lt;tt&gt;compareTo()&lt;/tt&gt; Method&lt;/b&gt;&lt;/h4&gt; &lt;table border="2" cellpadding="2" cellspacing="2"&gt;   &lt;col width="92"&gt; &lt;col width="126"&gt;    &lt;tbody&gt;&lt;tr valign="TOP"&gt;      &lt;td colspan="1" rowspan="1" width="92" valign="TOP"&gt;        &lt;p&gt;&lt;b&gt;&lt;tt&gt;s2.compareTo(s1)&lt;/tt&gt;&lt;/b&gt;&lt;/p&gt;     &lt;/td&gt;     &lt;td colspan="1" rowspan="1" width="126" valign="TOP"&gt;        &lt;p&gt;&lt;b&gt;Return Value&lt;/b&gt;&lt;/p&gt;     &lt;/td&gt;   &lt;/tr&gt;   &lt;tr valign="TOP"&gt;      &lt;td colspan="1" rowspan="1" width="92" valign="TOP"&gt;        &lt;p&gt;&lt;tt&gt;s1&lt;/tt&gt; &lt; &lt;tt&gt;s2&lt;/tt&gt;&lt;/p&gt;     &lt;/td&gt;     &lt;td colspan="1" rowspan="1" width="126" valign="TOP"&gt;        &lt;p&gt;&lt;&gt;     &lt;/p&gt;&lt;/td&gt;   &lt;/tr&gt;   &lt;tr valign="TOP"&gt;      &lt;td colspan="1" rowspan="1" width="92" valign="TOP"&gt;        &lt;p&gt;&lt;tt&gt;s1&lt;/tt&gt; equals &lt;tt&gt;s2&lt;/tt&gt;&lt;/p&gt;     &lt;/td&gt;     &lt;td colspan="1" rowspan="1" width="126" valign="TOP"&gt;        &lt;p&gt;0&lt;/p&gt;     &lt;/td&gt;   &lt;/tr&gt;   &lt;tr valign="TOP"&gt;      &lt;td colspan="1" rowspan="1" width="92" valign="TOP"&gt;        &lt;p&gt;&lt;tt&gt;s1&lt;/tt&gt; &gt; &lt;tt&gt;s2&lt;/tt&gt;&lt;/p&gt;     &lt;/td&gt;     &lt;td colspan="1" rowspan="1" width="126" valign="TOP"&gt;        &lt;p&gt;&gt; 0&lt;/p&gt;     &lt;/td&gt;   &lt;/tr&gt; &lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;p&gt;For example, if &lt;tt&gt;s1&lt;/tt&gt; is &lt;tt&gt;"cat"&lt;/tt&gt; and &lt;tt&gt;s2&lt;/tt&gt; is &lt;tt&gt;"dog"&lt;/tt&gt;, the function will return a number less than 0. In the &lt;tt&gt;objectSort.java&lt;/tt&gt; program, this method is used to compare the last name &lt;tt&gt;of a[in-1]&lt;/tt&gt; with the last name of &lt;tt&gt;temp&lt;/tt&gt;.&lt;/p&gt; &lt;h3&gt;Stability&lt;/h3&gt; &lt;p&gt;Sometimes it matters what happens to data items that have equal keys. For example, you may have employee data arranged alphabetically by last names. (That is, the last names were used as key values in the sort.) Now you want to sort the data by ZIP code, but you want all the items with the same ZIP code to continue to be sorted by last names. You want the algorithm to sort only what needs to be sorted, and leave everything else in its original order. Some sorting algorithms retain this secondary ordering; they're said to be stable.&lt;/p&gt; &lt;p&gt;All the algorithms in this chapter are stable. For example, notice the output of the &lt;tt&gt;objectSort.java&lt;/tt&gt; program (Listing 3.4). Three persons have the last name of Smith. Initially, the order is Doc Smith, Lorraine Smith, and Paul Smith. After the sort, this ordering is preserved, despite the fact that the various Smith objects have been moved to new locations.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-3864400416472445553?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/3864400416472445553/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/11/sorting-objects.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/3864400416472445553'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/3864400416472445553'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/11/sorting-objects.html' title='Sorting Objects'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-6668586168358032796</id><published>2009-11-25T00:12:00.000-08:00</published><updated>2009-11-25T00:13:38.763-08:00</updated><title type='text'></title><content type='html'>Sorting maps in Java based on it’s values&lt;br /&gt;By paaloliver&lt;br /&gt;Ever needed to sort a Map type collection in Java ?&lt;br /&gt;Well i had to the other day and of course all the documentation pointed me in the direction of the SortedMap interface.&lt;br /&gt;However, this datastructure is sorted on its keys and not on its values, which was really what I wanted to accomplish, so how do you do that? After a bit of fiddeling I found something that worked. Maybe its useful to you:public class MapValueSort {&lt;br /&gt;/** inner class to do soring of the map **/&lt;br /&gt;private static class ValueComparer implements Comparator {&lt;br /&gt;private Map _data = null;&lt;br /&gt;public ValueComparer (Map data){&lt;br /&gt;super();&lt;br /&gt;_data = data;&lt;br /&gt;}&lt;br /&gt;public int compare(Object o1, Object o2) {&lt;br /&gt;String e1 = (String) _data.get(o1);&lt;br /&gt;String e2 = (String) _data.get(o2);&lt;br /&gt;return e1.compareTo(e2);&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;public static void main(String[] args){&lt;br /&gt;Map unsortedData = new HashMap();&lt;br /&gt;unsortedData.put("2", "DEF");&lt;br /&gt;unsortedData.put("1", "ABC");&lt;br /&gt;unsortedData.put("4", "ZXY");&lt;br /&gt;unsortedData.put("3", "BCD");&lt;br /&gt;SortedMap sortedData = new TreeMap(new MapValueSort.ValueComparer(unsortedData));&lt;br /&gt;printMap(unsortedData);&lt;br /&gt;sortedData.putAll(unsortedData);&lt;br /&gt;System.out.println();&lt;br /&gt;printMap(sortedData);&lt;br /&gt;}&lt;br /&gt;private static void printMap(Map data) {&lt;br /&gt;for (Iterator iter = data.keySet().iterator(); iter.hasNext();) {&lt;br /&gt;String key = (String) iter.next();&lt;br /&gt;System.out.println("Value/key:"+data.get(key)+"/"+key);&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;This should output something of the lines of:Value/key:BCD/3&lt;br /&gt;Value/key:DEF/2&lt;br /&gt;Value/key:ZXY/4&lt;br /&gt;Value/key:ABC/1&lt;br /&gt;Value/key:ABC/1&lt;br /&gt;Value/key:BCD/3&lt;br /&gt;Value/key:DEF/2&lt;br /&gt;Value/key:ZXY/4&lt;br /&gt;Where the bottom last four lines obviously is sorted on the map’s values and not it’s keys.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-6668586168358032796?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/6668586168358032796/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/11/sorting-maps-in-java-based-on-its.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/6668586168358032796'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/6668586168358032796'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/11/sorting-maps-in-java-based-on-its.html' title=''/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-4281355767847349228</id><published>2009-11-25T00:09:00.000-08:00</published><updated>2009-11-25T00:12:18.143-08:00</updated><title type='text'></title><content type='html'>&lt;p&gt;In this program you will learn how to sort words in a String. The sorting will be done in ascending order. We are going to use sort() method of String class in Java. The description of the code is given below for the usage of the method.&lt;/p&gt;&lt;p&gt;&lt;br /&gt;Description of the code:&lt;br /&gt;Here, you will get to know about the sort() method through the following java program. In the program code given below, we have taken a String. First of all we will convert that string in array of characters. For this we have used toCharArray(); method. After that we have used sort(); method to sort that array of characters. &lt;/p&gt;&lt;p&gt;&lt;br /&gt;The code of the program is given below:&lt;/p&gt;&lt;p&gt;&lt;br /&gt;import java.util.*;&lt;/p&gt;&lt;p&gt;import java.io.*;&lt;/p&gt;&lt;p&gt;import java.lang.String;&lt;/p&gt;&lt;p&gt;public class SortWords{ &lt;/p&gt;&lt;p&gt;public static void main(String args[]){ &lt;/p&gt;&lt;p&gt;String str = "This is my new string"; &lt;/p&gt;&lt;p&gt;char[] content = str.toCharArray(); &lt;/p&gt;&lt;p&gt;java.util.Arrays.sort(content); &lt;/p&gt;&lt;p&gt;String sorted = new String(content); &lt;/p&gt;&lt;p&gt;System.out.println(content); &lt;/p&gt;&lt;p&gt;}&lt;/p&gt;&lt;p&gt;}&lt;br /&gt;Output of the program:&lt;/p&gt;&lt;p&gt;&lt;br /&gt;C:\unique&gt;javc SortWords&lt;/p&gt;&lt;p&gt;C:\unique&gt;java SortWordsTeghiiimnnrssstwy&lt;/p&gt;&lt;p&gt;C:\unique&gt; &lt;/p&gt;&lt;p&gt;&lt;br /&gt;&lt;a href="http://www.roseindia.net/java/string-examples/SortWords.java" roundtrip="0" lastvisited="0"&gt;&lt;span style="font-size:130%;"&gt;Download this example.&lt;/span&gt;&lt;/a&gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-4281355767847349228?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/4281355767847349228/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/11/in-this-program-you-will-learn-how-to.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/4281355767847349228'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/4281355767847349228'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/11/in-this-program-you-will-learn-how-to.html' title=''/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-9187506078720908335</id><published>2009-11-25T00:08:00.000-08:00</published><updated>2009-11-25T00:09:19.173-08:00</updated><title type='text'>Sorting a List</title><content type='html'>&lt;span style="font-size:180%;"&gt;&lt;strong&gt;Sorting a List&lt;/strong&gt;&lt;/span&gt; // Create a list&lt;br /&gt;String[] strArray = new String[] {"z", "a", "C"};&lt;br /&gt;List list = Arrays.asList(strArray);&lt;br /&gt;&lt;br /&gt;// Sort&lt;br /&gt;Collections.sort(list);&lt;br /&gt;// C, a, z&lt;br /&gt;&lt;br /&gt;// Case-insensitive sort&lt;br /&gt;Collections.sort(list, String.CASE_INSENSITIVE_ORDER);&lt;br /&gt;// a, C, z&lt;br /&gt;&lt;br /&gt;// Reverse-order sort&lt;br /&gt;Collections.sort(list, Collections.reverseOrder());&lt;br /&gt;// z, a, C&lt;br /&gt;&lt;br /&gt;// Case-insensitive reverse-order sort&lt;br /&gt;Collections.sort(list, String.CASE_INSENSITIVE_ORDER);&lt;br /&gt;Collections.reverse(list);&lt;br /&gt;// z, C, a&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-9187506078720908335?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/9187506078720908335/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/11/sorting-list.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/9187506078720908335'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/9187506078720908335'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/11/sorting-list.html' title='Sorting a List'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-8129980261007032757</id><published>2009-11-24T12:14:00.000-08:00</published><updated>2009-11-24T12:15:05.611-08:00</updated><title type='text'>Sorting Arrays</title><content type='html'>&lt;h1&gt;Sorting Arrays&lt;br /&gt;&lt;/h1&gt;    &lt;h2&gt;Why you shouldn't write your own sort&lt;/h2&gt; &lt;p&gt;&lt;b&gt;Good student problem.&lt;/b&gt;  A favorite computer science topic it &lt;i&gt;sorting&lt;/i&gt;, putting a collection of data in some order.  Typically this is done for arrays.  Textbooks cover both the slow, O(n&lt;sup&gt;2&lt;/sup&gt;), sorts (eg, selection, insertion, and bubble sorts) and fast, O(n log n), sorts (quick sort, heap sort, etc).  These are interesting problems, give students a lot of practice with arrays, bring up important tradeoffs, and are generally quite educational. &lt;/p&gt;  &lt;p&gt;&lt;b&gt;Bad professional pratice.&lt;/b&gt;  However, the Java library already has sort methods that are more efficient, more general, and more correct than anything you are likely to write yourself.  And they are already written.  Professional programmers use one of the &lt;code&gt;java.util.Arrays.sort()&lt;/code&gt; methods; they do not write their own, except perhaps in unusual cases.  &lt;/p&gt;  &lt;p&gt;&lt;span class="leadin"&gt;Other data structures.&lt;/span&gt;  There are sort methods in the &lt;code&gt;java.util.Collections&lt;/code&gt; class which can be used to sort other kinds of data structures (eg, ArrayList), and there are data structures such as &lt;code&gt;TreeMap&lt;/code&gt; that keep elements  sorted based on a key. &lt;/p&gt;    &lt;h2&gt;Sorting Arrays with &lt;code&gt;Arrays.sort(...)&lt;/code&gt;&lt;/h2&gt; &lt;p&gt;The &lt;code&gt;java.util.Arrays&lt;/code&gt; class has static  methods for sorting arrays, both arrays of primitive types and object types. The sort method can be applied to entire arrays, or only a particular range. For object types you can supply a &lt;i&gt;comparator&lt;/i&gt; to define how the sort should be performed. &lt;/p&gt;   &lt;table summary="string functions" border="0" cellpadding="0" cellspacing="0"&gt; &lt;tbody&gt;&lt;tr&gt;&lt;th&gt;Method&lt;/th&gt;&lt;th&gt;Description&lt;/th&gt;&lt;/tr&gt;  &lt;tr valign="top"&gt;&lt;td colspan="2" class="rowheader"&gt;&lt;i&gt;Arrays sort methods&lt;/i&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td&gt;&lt;code&gt;Arrays.sort(&lt;i&gt;pa&lt;/i&gt;);&lt;/code&gt;&lt;/td&gt;&lt;td&gt;Sorts the elements of the                                               array of a primitive type                                              into ascending order using their natural ordering.&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td&gt;&lt;code&gt;Arrays.sort(&lt;i&gt;pa&lt;/i&gt;, &lt;i&gt;from&lt;/i&gt;, &lt;i&gt;to&lt;/i&gt;);&lt;/code&gt;&lt;/td&gt;                                             &lt;td&gt;Sorts the elements &lt;i&gt;pa[from]&lt;/i&gt;...&lt;i&gt;pa[to-1]&lt;/i&gt;                                               of a primitive type.                                              into ascending order.&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td&gt;&lt;code&gt;Arrays.sort(&lt;i&gt;oa&lt;/i&gt;);&lt;/code&gt;&lt;/td&gt;&lt;td&gt;Sorts the elements of the array of an object type                                              into ascending order, using the order defined                                              by &lt;code&gt;Comparable&lt;/code&gt; interface, which                                              defines the &lt;code&gt;compareTo&lt;/code&gt; method.                                              Note that many Java classes such as                                               &lt;code&gt;String&lt;/code&gt; (but not &lt;code&gt;StringBuffer&lt;/code&gt;),                                              &lt;code&gt;Double&lt;/code&gt;, &lt;code&gt;BigInteger&lt;/code&gt;, etc                                              implement &lt;code&gt;Comparable&lt;/code&gt;.&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td&gt;&lt;code&gt;Arrays.sort(&lt;i&gt;oa&lt;/i&gt;, &lt;i&gt;from&lt;/i&gt;, &lt;i&gt;to&lt;/i&gt;);&lt;/code&gt;&lt;/td&gt;                                             &lt;td&gt;Sorts the elements of the array, in the range &lt;i&gt;from&lt;/i&gt;...&lt;i&gt;to&lt;/i&gt; of an object type                                              into ascending order.&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td&gt;&lt;code&gt;Arrays.sort(&lt;i&gt;oa&lt;/i&gt;, &lt;i&gt;comp&lt;/i&gt;);&lt;/code&gt;&lt;/td&gt;&lt;td&gt;Sorts the elements of the array of an object type                                              into ascending order, using the Comparator &lt;i&gt;comp&lt;/i&gt;.&lt;/td&gt;&lt;/tr&gt; &lt;tr valign="top"&gt;&lt;td nowrap="nowrap"&gt;&lt;code&gt;Arrays.sort(&lt;i&gt;oa&lt;/i&gt;, &lt;i&gt;from&lt;/i&gt;, &lt;i&gt;to&lt;/i&gt;, &lt;i&gt;comp&lt;/i&gt;);&lt;/code&gt;&lt;/td&gt;                                             &lt;td&gt;Sorts the elements of the array, in the range &lt;i&gt;from&lt;/i&gt;...&lt;i&gt;to&lt;/i&gt; of an object type                                              into ascending order using the Comparator &lt;i&gt;comp&lt;/i&gt;.&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt;&lt;/table&gt;  &lt;h2&gt;Example - Sorting arrays using Arrays.sort()&lt;/h2&gt; &lt;p&gt;This example sorts an array of Strings and an array of doubles.   All object types that implement &lt;i&gt;Comparable&lt;/i&gt; (ie, defines &lt;code&gt;compareTo()&lt;/code&gt; method), can be sorted with using a comparator. The &lt;code&gt;Arrays.sort()&lt;/code&gt; method is also defined for primitive arrays. &lt;/p&gt;  &lt;table summary="" border="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td valign="top"&gt;&lt;pre class="example2"&gt;  1&lt;br /&gt; 2&lt;br /&gt; 3&lt;br /&gt; 4&lt;br /&gt; 5&lt;br /&gt; 6&lt;br /&gt; 7&lt;br /&gt; 8&lt;br /&gt; 9&lt;br /&gt;10&lt;br /&gt;11&lt;br /&gt;12&lt;br /&gt;13&lt;br /&gt;14&lt;br /&gt;15&lt;br /&gt;16&lt;br /&gt;17&lt;br /&gt;18&lt;br /&gt;19&lt;br /&gt;20&lt;br /&gt;21&lt;br /&gt;&lt;/pre&gt;&lt;/td&gt;&lt;td valign="top"&gt; &lt;div class="file"&gt;&lt;pre&gt;// File   : data-arrays/dblsort/Dblsrt.java&lt;br /&gt;// Purpose: To show how Arrays.sort() works with arrays&lt;br /&gt;//          of both primitive and object values.&lt;br /&gt;// Author : Fred Swartz 2006-08-23.  Public domain.&lt;br /&gt;&lt;br /&gt;&lt;span class="hiliteu"&gt;import java.util.Arrays;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;public class Dblsrt {&lt;br /&gt;   //========================================================= main&lt;br /&gt;   public static void main(String[] args) {&lt;br /&gt;       //... 1. Sort strings - or any other Comparable objects.&lt;br /&gt;       String[] names = {"Zoe", "Alison", "David"};&lt;br /&gt;       &lt;span class="hiliteu"&gt;Arrays.sort(names);&lt;/span&gt;&lt;br /&gt;       System.out.println(Arrays.toString(names));&lt;br /&gt;&lt;br /&gt;       //... 2. Sort doubles or other primitives.&lt;br /&gt;       double[] lengths = {120.0, 0.5, 0.0, 999.0, 77.3};&lt;br /&gt;       &lt;span class="hiliteu"&gt;Arrays.sort(lengths);&lt;/span&gt;&lt;br /&gt;       System.out.println(Arrays.toString(lengths));&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt; &lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;  &lt;h3&gt;Output from above program&lt;/h3&gt; &lt;pre class="fragment"&gt;[Alison, David, Zoe]&lt;br /&gt;[0.0, 0.5, 77.3, 120.0, 999.0]&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-8129980261007032757?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/8129980261007032757/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/11/sorting-arrays.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/8129980261007032757'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/8129980261007032757'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/11/sorting-arrays.html' title='Sorting Arrays'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-4531728890755967091</id><published>2009-11-24T12:12:00.000-08:00</published><updated>2009-11-24T12:13:40.114-08:00</updated><title type='text'>Selection Sort</title><content type='html'>&lt;h1&gt;Selection Sort&lt;/h1&gt; &lt;p&gt;    NOTE: You should never write your own sort.    Use the &lt;code&gt;java.util.Arrays.sort(...)&lt;/code&gt; or     &lt;code&gt;java.util.Collections.sort(...)&lt;/code&gt;.    &lt;/p&gt;     &lt;p&gt;&lt;b&gt;Two nested loops.&lt;/b&gt;  Like all simple sorts, selection sort is implemented    with two nested loops.    &lt;/p&gt;     &lt;h2&gt;Simple selection sort&lt;/h2&gt; &lt;p&gt;The basic idea is to look at each element in the array, and for each element look at all remaining elements to see if there is something smaller that should be in this position.  If there is, exchange the two values. &lt;/p&gt;  &lt;pre class="fragment"&gt;public static void selectionSort1(int[] x) {&lt;br /&gt;   for (int i=0; i&lt;x.length-1; i++) {&lt;br /&gt;       for (int j=i+1; j&lt;x.length; j++) {&lt;br /&gt;           if (x[i] &gt; x[j]) {&lt;br /&gt;               //... Exchange elements&lt;br /&gt;               int temp = x[i];&lt;br /&gt;               x[i] = x[j];&lt;br /&gt;               x[j] = temp;&lt;br /&gt;           }&lt;br /&gt;       }&lt;br /&gt;   }&lt;br /&gt;}&lt;/pre&gt;          &lt;h2&gt;More efficient selection sort - Move every value only once&lt;/h2&gt; &lt;p&gt;This more efficient variation of selection sort remembers the    index of the smallest element that it finds in each pass.    At the end of each pass it makes one exchange, if necessary.    This is more efficient, but    you shouldn't be writing your own sort - use &lt;code&gt;java.util.Arrays.sort(...)&lt;/code&gt;!    &lt;/p&gt;     &lt;pre class="fragment"&gt;public static void selectionSort2(int[] x) {&lt;br /&gt;   for (int i=0; i&lt;x.length-1; i++) {&lt;br /&gt;       int minIndex = i;      // Index of smallest remaining value.&lt;br /&gt;       for (int j=i+1; j&lt;x.length; j++) {&lt;br /&gt;           if (x[minIndex] &gt; x[j]) {&lt;br /&gt;               minIndex = j;  // Remember index of new minimum&lt;br /&gt;           }&lt;br /&gt;       }&lt;br /&gt;       if (minIndex != i) {&lt;br /&gt;           //...  Exchange current element with smallest remaining.&lt;br /&gt;           int temp = x[i];&lt;br /&gt;           x[i] = x[minIndex];&lt;br /&gt;           x[minIndex] = temp;&lt;br /&gt;       }&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;span style="font-size:78%;"&gt;http://www.leepoint.net/notes-java/data/arrays/31arrayselectionsort.html&lt;/span&gt;&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-4531728890755967091?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/4531728890755967091/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/11/selection-sort.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/4531728890755967091'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/4531728890755967091'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/11/selection-sort.html' title='Selection Sort'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-1423275709786542248</id><published>2009-11-24T12:03:00.000-08:00</published><updated>2009-11-24T12:11:57.693-08:00</updated><title type='text'>Bubble sort</title><content type='html'>&lt;h1&gt;Bubble Sorts&lt;/h1&gt;  &lt;p&gt;People like bubble sorts -- could it be the name?   One nice aspect of bubble sorts is that they can quit early if the elements are almost sorted. &lt;/p&gt; &lt;p&gt;NOTE: As always, it's better if you don't write your own sorts.  Java has better sort methods in  &lt;code&gt;java.util.Arrays.sort(...)&lt;/code&gt; and &lt;code&gt;java.util.Collections.sort(...)&lt;/code&gt;. But sorts are excellent practice, and are a technique that all students are expected to understand to some extent. &lt;/p&gt;  &lt;h2&gt;Bubble Sort -- fixed number of passes&lt;/h2&gt; &lt;p&gt;This version of bubble sort makes a fixed number of     passes (length of the array - 1).  Each inner loop is    one shorter than the previous one.    &lt;/p&gt; &lt;pre class="example"&gt;public static void bubbleSort1(int[] x) {&lt;br /&gt;   int n = x.length;&lt;br /&gt;   for (int pass=1; pass &lt; n; pass++) {  // count how many times&lt;br /&gt;       // This next loop becomes shorter and shorter&lt;br /&gt;       for (int i=0; i &lt; n-pass; i++) {&lt;br /&gt;           if (x[i] &gt; x[i+1]) {&lt;br /&gt;               // exchange elements&lt;br /&gt;               int temp = x[i];  x[i] = x[i+1];  x[i+1] = temp;&lt;br /&gt;           }&lt;br /&gt;       }&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;      &lt;h2&gt;Bubble Sort -- stop when no exchanges&lt;/h2&gt; &lt;p&gt;This version of bubble sort continues making passes over     the array as long as there were any exchanges.      If the array is already sorted, this sort will stop after only    one pass.    &lt;/p&gt; &lt;pre class="example"&gt;public static void bubbleSort2(int[] x) {&lt;strong class="color"&gt;&lt;br /&gt;   boolean doMore = true;&lt;br /&gt;   while (doMore) {&lt;br /&gt;       doMore = false;  // assume this is last pass over array&lt;/strong&gt;&lt;br /&gt;       for (int i=0; i&lt;x.length-1; i++) {&lt;br /&gt;           if (x[i] &gt; x[i+1]) {&lt;br /&gt;              // exchange elements&lt;br /&gt;              int temp = x[i];  x[i] = x[i+1];  x[i+1] = temp;&lt;strong class="color"&gt;&lt;br /&gt;              doMore = true;  // after an exchange, must look again &lt;/strong&gt;&lt;br /&gt;           }&lt;br /&gt;       }&lt;br /&gt;   }&lt;br /&gt;}&lt;/pre&gt;       &lt;h2&gt;Bubble Sort -- stop when no exchanges, shorter range each time&lt;/h2&gt; &lt;p&gt;This version of bubble sort combines ideas from the previous versions.    It stops when there are no more exchanges, and it also sorts a smaller    range each time.    &lt;/p&gt; &lt;pre class="example"&gt;public static void bubbleSort3(int[] x) {&lt;br /&gt;   int n = x.length;&lt;br /&gt;   boolean doMore = true;&lt;br /&gt;   while (doMore) {&lt;br /&gt;       n--;&lt;br /&gt;       doMore = false;  // assume this is our last pass over the array&lt;br /&gt;       for (int i=0; i&lt;n; i++) {&lt;br /&gt;           if (x[i] &gt; x[i+1]) {&lt;br /&gt;               // exchange elements&lt;br /&gt;               int temp = x[i];  x[i] = x[i+1];  x[i+1] = temp;&lt;br /&gt;               doMore = true;  // after an exchange, must look again&lt;br /&gt;           }&lt;br /&gt;       }&lt;br /&gt;   }&lt;br /&gt;}//end method bubbleSort3&lt;/pre&gt;      &lt;h2&gt;Bubble Sort -- Sort only necessary range&lt;/h2&gt; &lt;p&gt;After a pass on bubble sort, it's only necessary to sort    from just below the first exchange to just after the last exchange,    because everything that wasn't exchanged must be in the correct order.    This version of bubble sort remembers the lowest and highest locations    where there was an exchange, and sorts only that part of the array.    Although it is a little more complicated, it is more efficient    than the other bubble sorts.    &lt;/p&gt; &lt;pre class="example"&gt;public static void bubbleSort4(int[] x) {&lt;br /&gt;   int newLowest = 0;            // index of first comparison&lt;br /&gt;   int newHighest = x.length-1;  // index of last comparison&lt;br /&gt;&lt;br /&gt;   while (newLowest &lt; newHighest) {&lt;br /&gt;       int highest = newHighest;&lt;br /&gt;       int lowest  = newLowest;&lt;br /&gt;       newLowest = x.length;    // start higher than any legal index&lt;br /&gt;       for (int i=lowest; i&lt;highest; i++) {&lt;br /&gt;           if (x[i] &gt; x[i+1]) {&lt;br /&gt;              // exchange elements&lt;br /&gt;              int temp = x[i];  x[i] = x[i+1];  x[i+1] = temp;&lt;br /&gt;              if (i&lt;newLowest) {&lt;br /&gt;                  newLowest = i-1;&lt;br /&gt;                  if (newLowest &lt; 0) {&lt;br /&gt;                      newLowest = 0;&lt;br /&gt;                  }&lt;br /&gt;              } else if (i&gt;newHighest) {&lt;br /&gt;                  newHighest = i+1;&lt;br /&gt;              }&lt;br /&gt;           }&lt;br /&gt;       }&lt;br /&gt;   }&lt;br /&gt;}//end method bubbleSort4&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size:78%;"&gt;http://www.leepoint.net/notes-java/data/arrays/32arraybubblesort.html&lt;/span&gt;&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-1423275709786542248?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/1423275709786542248/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/11/bubble-sort.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/1423275709786542248'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/1423275709786542248'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/11/bubble-sort.html' title='Bubble sort'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-5134260328282625546</id><published>2009-11-24T12:02:00.001-08:00</published><updated>2009-11-24T12:02:57.663-08:00</updated><title type='text'>Arrays.sort()</title><content type='html'>&lt;h2&gt;Example - Sorting arrays using Arrays.sort()&lt;/h2&gt; &lt;p&gt;This example sorts an array of Strings and an array of doubles.   All object types that implement &lt;i&gt;Comparable&lt;/i&gt; (ie, defines &lt;code&gt;compareTo()&lt;/code&gt; method), can be sorted with using a comparator. The &lt;code&gt;Arrays.sort()&lt;/code&gt; method is also defined for primitive arrays. &lt;/p&gt;  &lt;table summary="" border="0"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td valign="top"&gt;&lt;pre class="example2"&gt;  1&lt;br /&gt; 2&lt;br /&gt; 3&lt;br /&gt; 4&lt;br /&gt; 5&lt;br /&gt; 6&lt;br /&gt; 7&lt;br /&gt; 8&lt;br /&gt; 9&lt;br /&gt;10&lt;br /&gt;11&lt;br /&gt;12&lt;br /&gt;13&lt;br /&gt;14&lt;br /&gt;15&lt;br /&gt;16&lt;br /&gt;17&lt;br /&gt;18&lt;br /&gt;19&lt;br /&gt;20&lt;br /&gt;21&lt;br /&gt;&lt;/pre&gt;&lt;/td&gt;&lt;td valign="top"&gt; &lt;div class="file"&gt;&lt;pre&gt;// File   : data-arrays/dblsort/Dblsrt.java&lt;br /&gt;// Purpose: To show how Arrays.sort() works with arrays&lt;br /&gt;//          of both primitive and object values.&lt;br /&gt;// Author : Fred Swartz 2006-08-23.  Public domain.&lt;br /&gt;&lt;br /&gt;&lt;span class="hiliteu"&gt;import java.util.Arrays;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;public class Dblsrt {&lt;br /&gt;   //========================================================= main&lt;br /&gt;   public static void main(String[] args) {&lt;br /&gt;       //... 1. Sort strings - or any other Comparable objects.&lt;br /&gt;       String[] names = {"Zoe", "Alison", "David"};&lt;br /&gt;       &lt;span class="hiliteu"&gt;Arrays.sort(names);&lt;/span&gt;&lt;br /&gt;       System.out.println(Arrays.toString(names));&lt;br /&gt;&lt;br /&gt;       //... 2. Sort doubles or other primitives.&lt;br /&gt;       double[] lengths = {120.0, 0.5, 0.0, 999.0, 77.3};&lt;br /&gt;       &lt;span class="hiliteu"&gt;Arrays.sort(lengths);&lt;/span&gt;&lt;br /&gt;       System.out.println(Arrays.toString(lengths));&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt; &lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;  &lt;h3&gt;Output from above program&lt;/h3&gt; &lt;pre class="fragment"&gt;[Alison, David, Zoe]&lt;br /&gt;[0.0, 0.5, 77.3, 120.0, 999.0]&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-5134260328282625546?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/5134260328282625546/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/11/arrayssort.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/5134260328282625546'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/5134260328282625546'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/11/arrayssort.html' title='Arrays.sort()'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6326223989111236657.post-8779446239039347516</id><published>2009-11-23T04:57:00.000-08:00</published><updated>2009-11-23T05:12:33.421-08:00</updated><title type='text'>Sorting Algorithms</title><content type='html'>&lt;h1&gt;Sorting Algorithms&lt;/h1&gt; &lt;hr /&gt;  &lt;p&gt; We all know that Quicksort is one of the fastest algorithms for sorting.  It's not often, however, that we get a chance to see exactly &lt;em&gt;how&lt;/em&gt; fast Quicksort really is.  The following applets chart the progress of several common sorting algorithms while sorting an array of data using &lt;b&gt;in-place&lt;/b&gt; algorithms.  This means that the algorithms do not allocate additional storage to hold temporary results: they sort the data in place.&lt;/p&gt;  &lt;p&gt; Some of these sorts are very stupid or very slow and should not be used in code.  The use of Bubblesort is deprecated.  So don't use Bubblesort!  Also, don't use Swapsort! It is only a demonstration of the amount of time Java takes to swap n elements.  &lt;/p&gt;  &lt;p&gt; In-Place Mergesort is yet another abomination.  Mergesort is supposed to run in O(n log n), but the implementation here runs in O(n * n).  This is because a temporary scratch array is not used.  As with &lt;b&gt;most&lt;/b&gt; of the examples here, In-Place Mergesort sorts the elements in the array without using additional storage (other than the stack used for the recursive calls, and temporary variables).  Jack Snoeyink has provided me with a the Double Storage mergesort algorithm sort implementation that uses a scratch array.&lt;/p&gt;  &lt;p&gt;New: Radix sort by Alvin Raj, August 13, 2002.&lt;/p&gt;  &lt;em&gt;&lt;/em&gt;&lt;em&gt;&lt;/em&gt;&lt;dl&gt;&lt;dt&gt; &lt;a href="http://people.cs.ubc.ca/%7Eharrison/Java/BubbleSort2Algorithm.java.html"&gt;&lt;b&gt;Bubble Sort&lt;/b&gt;        (by James Gosling and Jason Harrison)&lt;/a&gt;&lt;/dt&gt;&lt;dd&gt;&lt;br /&gt;&lt;/dd&gt;&lt;dt&gt; &lt;a href="http://people.cs.ubc.ca/%7Eharrison/Java/BidirectionalBubbleSortAlgorithm.java.html"&gt;&lt;b&gt;Bi-Directional        Bubble Sort&lt;/b&gt; (by James Gosling)&lt;/a&gt;&lt;/dt&gt;&lt;dd&gt;&lt;br /&gt;&lt;/dd&gt;&lt;dt&gt; &lt;a href="http://people.cs.ubc.ca/%7Eharrison/Java/SelectionSortAlgorithm.java.html"&gt;&lt;b&gt;Selection        Sort&lt;/b&gt; (by Jason Harrison)&lt;/a&gt;&lt;/dt&gt;&lt;dd&gt;&lt;br /&gt;&lt;/dd&gt;&lt;dt&gt; &lt;a href="http://people.cs.ubc.ca/%7Eharrison/Java/ShakerSortAlgorithm.java.html"&gt;&lt;b&gt;Shaker        Sort&lt;/b&gt; (by Jason Harrison)&lt;/a&gt;&lt;/dt&gt;&lt;dd&gt;&lt;br /&gt;&lt;/dd&gt;&lt;dt&gt; &lt;a href="http://people.cs.ubc.ca/%7Eharrison/Java/InsertionSortAlgorithm.java.html"&gt;&lt;b&gt;Insertion        Sort&lt;/b&gt; (by Jason Harrison)&lt;/a&gt;&lt;/dt&gt;&lt;dd&gt;&lt;br /&gt;&lt;/dd&gt;&lt;dt&gt; &lt;a href="http://people.cs.ubc.ca/%7Eharrison/Java/MergeSortAlgorithm.java.html"&gt;&lt;b&gt;In-Place Merge Sort&lt;/b&gt; (by        Jason Harrison)&lt;/a&gt;&lt;/dt&gt;&lt;dd&gt;&lt;br /&gt;&lt;/dd&gt;&lt;dt&gt; &lt;a href="http://people.cs.ubc.ca/%7Eharrison/Java/ExtraStorageMergeSortAlgorithm.java.html"&gt;        &lt;b&gt;Double Storage Merge Sort&lt;/b&gt;        (by Jack Snoeyink)&lt;/a&gt;&lt;/dt&gt;&lt;dd&gt;&lt;br /&gt;&lt;/dd&gt;&lt;dt&gt; &lt;a href="http://people.cs.ubc.ca/%7Eharrison/Java/CombSort11Algorithm.java.html"&gt;&lt;b&gt;Comb Sort 11&lt;/b&gt; (by        Jason Harrison)&lt;/a&gt;&lt;/dt&gt;&lt;dd&gt;&lt;br /&gt;&lt;/dd&gt;&lt;dt&gt; &lt;a href="http://people.cs.ubc.ca/%7Eharrison/Java/ShellSortAlgorithm.java.html"&gt;&lt;b&gt;Shell Sort&lt;/b&gt; (by        Jason Harrison)&lt;/a&gt;&lt;/dt&gt;&lt;dd&gt;&lt;br /&gt;&lt;/dd&gt;&lt;dt&gt; &lt;a href="http://people.cs.ubc.ca/%7Eharrison/Java/HeapSortAlgorithm.java.html"&gt;&lt;b&gt;Heap Sort&lt;/b&gt; (by        Jason Harrison)&lt;/a&gt;&lt;/dt&gt;&lt;dd&gt;&lt;br /&gt;&lt;/dd&gt;&lt;dt&gt; &lt;a href="http://people.cs.ubc.ca/%7Eharrison/Java/QSortAlgorithm.java.html"&gt;&lt;b&gt;Quick Sort&lt;/b&gt; (by        James Gosling)&lt;/a&gt;&lt;/dt&gt;&lt;dd&gt;&lt;br /&gt;&lt;/dd&gt;&lt;dt&gt; &lt;a href="http://people.cs.ubc.ca/%7Eharrison/Java/QubbleSortAlgorithm.java.html"&gt;&lt;b&gt;Quick Sort with        Bubblesort&lt;/b&gt; (by Jim Boritz)&lt;/a&gt;&lt;/dt&gt;&lt;dd&gt;&lt;br /&gt;&lt;/dd&gt;&lt;dt&gt; &lt;a href="http://people.cs.ubc.ca/%7Eharrison/Java/EQSortAlgorithm.java.html"&gt;&lt;b&gt;Enhanced Quick Sort&lt;/b&gt;        (by Jim Boritz)&lt;/a&gt;&lt;/dt&gt;&lt;dd&gt;&lt;br /&gt;&lt;/dd&gt;&lt;dt&gt; &lt;a href="http://people.cs.ubc.ca/%7Eharrison/Java/FastQSortAlgorithm.java.html"&gt;&lt;b&gt;Fast Quick Sort&lt;/b&gt;        (by Denis Ahrens)&lt;/a&gt;&lt;/dt&gt;&lt;dt&gt;&lt;a href="http://people.cs.ubc.ca/%7Eharrison/Java/FastQSortAlgorithm.java.html"&gt;&lt;/a&gt;        &lt;p&gt;   &lt;/p&gt;&lt;a href="http://people.cs.ubc.ca/%7Eharrison/Java/RadixSortAlgorithm.java.html"&gt;&lt;b&gt;Radix Sort Algorithm&lt;/b&gt;        (by Alvin Raj)&lt;/a&gt;  &lt;a href="http://people.cs.ubc.ca/%7Eharrison/Java/LinkedQueue.java.html"&gt;LinkedQueue.java&lt;/a&gt;        and &lt;a href="http://people.cs.ubc.ca/%7Eharrison/Java/intNode.java.html"&gt;intNode.java&lt;/a&gt;        &lt;p&gt;   &lt;/p&gt;&lt;/dt&gt;&lt;/dl&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6326223989111236657-8779446239039347516?l=javasort.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasort.blogspot.com/feeds/8779446239039347516/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasort.blogspot.com/2009/11/sorting-algorithms.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/8779446239039347516'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6326223989111236657/posts/default/8779446239039347516'/><link rel='alternate' type='text/html' href='http://javasort.blogspot.com/2009/11/sorting-algorithms.html' title='Sorting Algorithms'/><author><name>LidiNG</name><uri>http://www.blogger.com/profile/18059502394623792654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_kckz4c0UF20/SxQjOId-sPI/AAAAAAAAHps/fPSYRqn1T7c/S220/DSC04973.JPG'/></author><thr:total>0</thr:total></entry></feed>
