Advertisement
Boyan5

Quick sort Topic 14

Jan 15th, 2021
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.54 KB | None | 0 0
  1. package com.array;
  2. import java.util.Arrays;
  3. import java.util.Scanner;
  4. import static com.array.quicksortmethods.quickSort;
  5. public class quicksortmain {
  6.     public static void main(String[] args) {
  7. Scanner input = new Scanner(System.in);
  8.         System.out.println("Input the number of elements /N/ :");
  9.         int N = input.nextInt();
  10.  
  11.         int[] arr = new int[N];
  12.  
  13.         for (int i = 0; i < N; i++) {
  14.             System.out.printf("Input element [%d] : ", i);
  15.             arr[i] = input.nextInt();
  16.         }
  17.  
  18.         System.out.println("Before sorting : " + Arrays.toString(arr));
  19.  
  20.         quickSort(arr,0,N - 1);
  21.  
  22.         System.out.println("After sorting : " + Arrays.toString(arr));
  23.     }
  24. }
  25.  
  26.  
  27.  
  28.  
  29.  
  30. package com.array;
  31. public class quicksortmethods {
  32.  
  33.     public static void quickSort(int[] arr,int low,int high){
  34.         if (low < high){
  35.  
  36.             int pi = partition(arr,low,high);
  37.  
  38.             quickSort(arr,low,pi-1);
  39.             quickSort(arr,pi+1,high);
  40.  
  41.         }
  42.     }
  43.  
  44.     public static int partition(int[] arr,int low , int high) {
  45. int pivot = arr[high];
  46. int i = low - 1;
  47.  
  48.         for (int j = low; j < high ; j++) {
  49.  
  50.             if (arr[j] < pivot){
  51.                 i++;
  52.                 //swap
  53.                 int temp = arr[j];
  54.                 arr[j] = arr[i];
  55.                 arr[i] = temp;
  56.  
  57.             }
  58.         }
  59.         //put the pivot element at the right position
  60.        int temp = arr[high];
  61.         arr[high] = arr[i + 1];
  62.         arr[i + 1] = temp;
  63.         return i + 1;
  64.     }
  65.  
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement