Created
March 19, 2021 16:48
-
-
Save stoyanovsh/2ca22c39923ab0197e70b945f529682f to your computer and use it in GitHub Desktop.
Sorting Array
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
| public class ArraySort { | |
| public static void main(String[] args) { | |
| int[] array = {1, 3, 1, 2, 5, 2, 1, 3}; | |
| sort(array); | |
| for (int i : array) { | |
| System.out.print(i + " "); | |
| } | |
| } | |
| private static void sort(int[] array) { | |
| sort(array, 0, array.length - 1); | |
| } | |
| private static void sort(int[] array, int left, int right) { | |
| if (left >= right) { | |
| return; | |
| } | |
| int pivot = array[(left + right) / 2]; | |
| int index = partition(array, left, right, pivot); | |
| sort(array, left, index - 1); | |
| sort(array, index, right); | |
| } | |
| private static int partition(int[] array, int left, int right, int pivot) { | |
| while (left <= right) { | |
| while (array[left] < pivot) { | |
| left++; | |
| } | |
| while (array[right] > pivot) { | |
| right--; | |
| } | |
| if (left <= right) { | |
| swap(array, left, right); | |
| left++; | |
| right--; | |
| } | |
| } | |
| return left; | |
| } | |
| private static void swap(int[] array, int left, int right) { | |
| int tmp = array[left]; | |
| array[left] = array[right]; | |
| array[right] = tmp; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment