JetBrains Academy: Quicksort in Java - Kamil-Jankowski/Learning-JAVA GitHub Wiki
JetBrains Academy: Quicksort in Java
Move the pivot:
For a given array and a given index of a pivot, you should implement the method moveThePivot
that rearranges the array and places the pivot in the right position, keeping in mind that the array would be part of Quicksort algorithm and eventually the array would be sorted in the ascending order.
import java.util.*;
public class Main {
public static void moveThePivot(int[] array, int pivotIndex) {
swap(array, pivotIndex, array.length - 1);
int pivot = array[array.length - 1]; // selected pivot value
int partitionIndex = 0; // the first element greater than the pivot
/* move large values into the right side of the array */
for (int i = 0; i < array.length; i++) {
if (array[i] < pivot) { // may be used '<' as well
swap(array, i, partitionIndex);
partitionIndex++;
}
}
swap(array, partitionIndex, array.length - 1); // put the pivot on a suitable position
}
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
/* Do not change code below */
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] array = Arrays.stream(scanner.nextLine().split(" "))
.mapToInt(Integer::parseInt).toArray();
int pivotIndex = scanner.nextInt();
moveThePivot(array, pivotIndex);
Arrays.stream(array).forEach(e -> System.out.print(e + " "));
}
}