Jacob_Thomas

Quick Sort

Jan 28th, 2021
526
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.20 KB | None | 0 0
  1. import java.util.*;
  2. class Quicksort{
  3.     public static void main(String args[]){
  4.         Scanner sc = new Scanner(System.in);
  5.         System.out.println("Enter size");
  6.         int n = sc.nextInt();
  7.         int arr[] = new int[n];
  8.         System.out.println("Enter the array");
  9.         for(int x = 0; x<n; x++){
  10.             arr[x] = sc.nextInt();
  11.         }
  12.         Quicksort q = new Quicksort();
  13.         q.sort(arr, 0, n-1);
  14.         System.out.println(Arrays.toString(arr));
  15.     }
  16.    
  17.     int partition(int arr[], int low, int high){
  18.         int temp;
  19.         int pivot = arr[high];
  20.         int x = low - 1;
  21.         for(int y = low; y<high; y++){
  22.             if(arr[y]<pivot){
  23.                 x = x + 1;
  24.                 temp = arr[y];
  25.                 arr[y] = arr[x];
  26.                 arr[x] = temp;
  27.             }
  28.         }
  29.         temp = arr[x+1];
  30.         arr[x+1] = arr[high];
  31.         arr[high] = temp;
  32.        
  33.         return (x+1);
  34.     }
  35.    
  36.     void sort(int arr[], int low, int high){
  37.         if(low < high){
  38.             int pivot = partition(arr, low, high);
  39.            
  40.             sort(arr, low, pivot-1);
  41.            
  42.             sort(arr, pivot+1, high);
  43.         }
  44.     }
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment