Created
January 12, 2019 08:27
-
-
Save dekaikiwi/7ab338fc6f5cb65a6a34719e8ace8e50 to your computer and use it in GitHub Desktop.
Implementation of QuickSort in Java.
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 jono.sorting; | |
import java.util.Arrays; | |
import java.util.stream.Stream; | |
public class QuickSorter { | |
public static void main(String[] args) { | |
QuickSorter sorter = new QuickSorter(); | |
int[] array = Stream.of(args[0].split(",")).mapToInt(Integer::parseInt).toArray(); | |
sorter.sort(array); | |
System.out.println(Arrays.toString(array)); | |
} | |
public void sort(int[] numbers) { | |
quickSort(numbers, 0, numbers.length - 1); | |
} | |
private void quickSort(int[] numbers, int left, int right) { | |
int divPoint, pivot; | |
if (left >= right) { | |
return; | |
} | |
System.out.printf("left: %d right: %d%n", left, right); | |
pivot = numbers[(left + right) / 2]; | |
divPoint = partition(numbers, left, right, pivot); | |
System.out.println("divPoint: " + divPoint); | |
quickSort(numbers, left, divPoint - 1); | |
quickSort(numbers, divPoint, right); | |
} | |
private int partition(int[] numbers, int left, int right, int pivot) { | |
while (left <= right) { | |
while (numbers[left] < pivot) { | |
left += 1; | |
} | |
while (numbers[right] > pivot) { | |
right -= 1; | |
} | |
if (left <= right) { | |
swap(numbers, left, right); | |
left += 1; | |
right -= 1; | |
} | |
} | |
return left; | |
} | |
private void swap(int[] numbers, int left, int right) { | |
int leftNum = numbers[left]; | |
int rightNum = numbers[right]; | |
numbers[left] = rightNum; | |
numbers[right] = leftNum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment