Download code

Jump to: navigation, search

Back to Quicksort_(Java)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

Quicksort.java

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Quicksort_(Java)?oldid=16417
14 */
15 
16 
17 
18 import static org.junit.Assert.assertArrayEquals;
19 import org.junit.Test;
20 public class Quicksort {
21 	
22 	static <T extends Comparable<? super T>> void quicksort(T[] array) {
23 		
24 		quicksort(array, 0, array.length - 1);
25 	}
26 	
27 	static <T extends Comparable<? super T>> void quicksort(T[] array, int left0, int right0) {
28 		
29 		int left = left0;
30 		int right = right0 + 1;
31 		T pivot, temp;
32 		
33 		pivot = array[left0];
34 		
35 		do {
36 			
37 			do left++; while (left <= right0 && array[left].compareTo(pivot) < 0);
38 			
39 			do right--; while (array[right].compareTo(pivot) > 0);
40 			
41 			if (left < right) {
42 				temp = array[left];
43 				array[left] = array[right];
44 				array[right] = temp;
45 			}
46 		}
47 		while (left <= right); 
48 		
49 		temp = array[left0];
50 		array[left0] = array[right];
51 		array[right] = temp;
52 		
53 		if (left0 < right) quicksort(array, left0, right);
54 		if (left < right0) quicksort(array, left, right0);
55 	}
56 	
57 	@Test
58 	public void integerSorting() {
59 		
60 		Integer[] array = { 5, 3, 4, 2, 1 };
61 		quicksort(array);
62 		Integer[] correct = { 1, 2, 3, 4, 5 };
63 		assertArrayEquals(correct, array);
64 
65 	}
66 	
67 	@Test
68 	public void floatSorting() {
69 		Float[] array = { 1.8F, 3.6F, 4F, 5F, 2F };
70 		quicksort(array);
71 		Float[] correct = { 1.8F, 2F, 3.6F, 4F, 5F };
72 		assertArrayEquals(correct, array);
73 	}
74 	
75 	@Test
76 	public void stringSorting() {
77 	    String[] array = {"Batman", "Spiderman", "Anthony", "Zoolander"};
78 	    quicksort(array);
79 	    String[] correct = {"Anthony", "Batman",  "Spiderman",  "Zoolander"};
80 	    assertArrayEquals(correct, array);
81 	}
82 }


hijacker
hijacker
hijacker
hijacker