Last active
February 26, 2020 10:27
-
-
Save iamdejan/3f36a02cd4445808d3ee7ec64d5c5d48 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
import java.util.Arrays; | |
import java.util.Random; | |
import java.util.Scanner; | |
class Solution { | |
private void swap(int[] numbers, int i, int j) { | |
int temp = numbers[i]; | |
numbers[i] = numbers[j]; | |
numbers[j] = temp; | |
} | |
private int getPartitionIndex(int[] numbers, int start, int end) { | |
int randomIndex = (new Random()).nextInt(end - start) + start; | |
swap(numbers, randomIndex, end); | |
int partition = numbers[end]; | |
int i = start - 1; | |
for(int j = start; j <= end - 1; j++) { | |
if(numbers[j] <= partition) { | |
swap(numbers, ++i, j); | |
} | |
} | |
swap(numbers, ++i, end); | |
return i; | |
} | |
private void sort(int[] numbers, int start, int end) { | |
if(start >= end) { | |
return; | |
} | |
int partitionIndex = getPartitionIndex(numbers, start, end); | |
System.out.printf("start = %d, end = %d, partitionIndex = %d\n", start, end, partitionIndex); | |
sort(numbers, start, partitionIndex - 1); | |
sort(numbers, partitionIndex + 1, end); | |
} | |
private void sort(int[] numbers) { | |
sort(numbers, 0, numbers.length - 1); | |
} | |
public Solution() { | |
Scanner reader = new Scanner(System.in); | |
int[] numbers = new int[20]; | |
for(int i = 0; i < numbers.length; i++) { | |
numbers[i] = (new Random()).nextInt(100); | |
} | |
System.out.println(Arrays.toString(numbers)); | |
sort(numbers); | |
System.out.println(Arrays.toString(numbers)); | |
} | |
public static void main(String[] args) { | |
new Solution(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment