Advertisement
Vasilena

ТЕМА 14

Jan 15th, 2021
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.50 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Scanner;
  3.  
  4. public class QuickSort {
  5.     public static void main(String[] args) {
  6.     Scanner scan = new Scanner(System.in);
  7.         System.out.println("Enter number of elements: ");
  8.     int N = scan.nextInt();
  9.     int[] arr = new int[N];
  10.         for (int i = 0; i < N; i++) {
  11.         System.out.print("Enter element " + i + " :");
  12.         arr[i] = Integer.parseInt(scan.next());
  13.     }
  14.     //print before//
  15.         System.out.println("BEFORE SORT: " + Arrays.toString(arr));
  16.  
  17.     quickSort(arr, 0, N -1);
  18.  
  19.     //print after//
  20.         System.out.println("AFTER SORT: " + Arrays.toString(arr));
  21.     }//end of main//
  22.  
  23.  
  24.     public static void quickSort(int[] arr, int low, int high){
  25.         if(low < high){
  26.             int pi = partition(arr, low, high);
  27.             quickSort(arr, low, pi - 1);
  28.             quickSort(arr, pi + 1, high);
  29.         }
  30.     }//end of quickSort//
  31.  
  32.     public static int partition(int[] arr, int low, int high){
  33.         int pivot = arr[high];
  34.         int i = low - 1;
  35.         for (int j = low; j < high; j++) {
  36.             if(arr[j] < pivot){
  37.                 i++;
  38.                 //swap//
  39.                 int temp = arr[j];
  40.                 arr[j] = arr[i];
  41.                 arr[i] = temp;
  42.             }
  43.         }
  44.         //put  the pivot element at the right position//
  45.         int temp = arr[high];
  46.         arr[high] = arr[i + 1];
  47.         arr[i + 1] = temp;
  48.         return i + 1;
  49.     }//end of partition//
  50. }//end of class//
  51.  
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement