Created
September 10, 2015 04:12
-
-
Save mchayapol/51e0a10fb96bd391280b to your computer and use it in GitHub Desktop.
Quick Sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package edu.au.scitech.sc2101; | |
| import java.util.Arrays; | |
| public class SortingUtility { | |
| public static void quickSort(int[] arr, int startIndex, int endIndex) { | |
| System.out.println( Arrays.toString( arr ) ); | |
| int pivotIndex = (startIndex + endIndex) / 2; | |
| int i = startIndex; | |
| int j = endIndex; | |
| while( !(i > j) ) { | |
| // travel from LHS (i) | |
| while( arr[i] < arr[pivotIndex] ) | |
| i++; | |
| // travel from RHS (j) | |
| while( arr[j] > arr[pivotIndex] ) | |
| j--; | |
| System.out.printf("%d %d\n", i, j); | |
| // swap the numbers | |
| if (i <= j) { | |
| int t = arr[i]; | |
| arr[i] = arr[j]; | |
| arr[j] = t; | |
| i++; | |
| j--; | |
| System.out.println( Arrays.toString( arr ) ); | |
| } | |
| } | |
| // divide 2 chunks of array | |
| // [startIndex .. j] and [i .. endIndex] | |
| if (startIndex < j) { | |
| System.out.printf("Dividing %d-%d",startIndex, j); | |
| quickSort(arr, startIndex, j); | |
| } | |
| if (i < endIndex) { | |
| System.out.printf("Dividing %d-%d",i, endIndex); | |
| quickSort(arr, i, endIndex); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package edu.au.scitech.sc2101; | |
| import static org.junit.Assert.*; | |
| import org.junit.Test; | |
| public class SortingUtilityTest { | |
| @Test | |
| public void testQuickSort() { | |
| int[] randomData1 = {1, 12, 5, 26, 7, 14, 3, 7, 2}; | |
| int[] expected = {1,2,3,5,7,7,12,14,26}; | |
| SortingUtility.quickSort(randomData1, 0, randomData1.length-1); | |
| assertArrayEquals(expected,randomData1); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment