SvilenVelikov

QuickSort

Jun 7th, 2020
886
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.45 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Scanner;
  3.  
  4. public class Qucksort {
  5.     public static void main(String[] args) {
  6.         Scanner sc = new Scanner(System.in);
  7.         int[] arr = Arrays.stream(sc.nextLine().split("\\s+")).mapToInt(x -> Integer.parseInt(x)).toArray();
  8.         quickSort(arr, 0, arr.length - 1);
  9.  
  10.         StringBuilder builder = new StringBuilder();
  11.         for (int num : arr) {
  12.             builder.append(num).append(" ");
  13.         }
  14.         System.out.println(builder.toString());
  15.     }
  16.  
  17.     // low is the start index
  18.     // high is the end index
  19.     private static void quickSort(int[] arr, int low, int high) {
  20.  
  21.         if (low < high) {
  22.             int pi = partition(arr, low, high);
  23.             quickSort(arr, low, pi - 1);
  24.             quickSort(arr, pi + 1, high);
  25.         }
  26.  
  27.     }
  28.  
  29.     private static int partition(int[] arr, int low, int high) {
  30.         int pivot = arr[high];
  31.         int i = (low - 1); // index of the smaller element
  32.         for (int j = low; j < high; j++) {
  33.             //If current lement is smaller or equal to pivot
  34.             if (arr[j] <= pivot) {
  35.                 i++;
  36.                 swap(arr, arr[i], arr[j]);
  37.             }
  38.         }
  39.  
  40.         swap(arr, arr[i + 1], pivot);
  41.  
  42.         return i + 1;
  43.     }
  44.  
  45.     private static void swap(int[] arr, int first, int second) {
  46.         int temp = arr[first];
  47.         arr[first] = arr[second];
  48.         arr[second] = temp;
  49.     }
  50.  
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment