Advertisement
unknown_0711

Untitled

Jul 18th, 2022
884
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. public class Main {
  6.     public static int[] ar;
  7.     public static void quicksort( int l, int h) {
  8.       // System.out.println(l + " " + h);
  9.         if(l<h) {
  10.          
  11.            int pi = partition(l,h);
  12.             quicksort(l,pi-1);
  13.             quicksort(pi+1,h);
  14.              
  15.               // if(l==4 && h==6)
  16.           for(int j=l; j<=h; j++) {
  17.                 System.out.print(ar[j]+" ");
  18.             }
  19.             System.out.println();
  20.            
  21.         }
  22.     }
  23.     public static int partition( int l, int h) {
  24.       int[] left,right;
  25.       int pivot = ar[l];
  26.       int lf = 0,rg = 0,eq = 1;
  27.       for(int i = l+1 ; i <= h ; i++){
  28.         if(ar[i] < pivot) lf++;
  29.         else if(ar[i] > pivot) rg++;
  30.         else eq++;
  31.       }
  32.       left = new int[lf];
  33.       int j = 0,k=0;
  34.       right = new int[rg];
  35.       for(int i = l+1 ; i <= h ; i++){
  36.         if(ar[i] < pivot) left[j++] = ar[i];
  37.         else if(ar[i] > pivot ) right[k++] = ar[i];
  38.       }
  39.  
  40.       for(int i = 0 ; i < lf ; i++) ar[l+i] = left[i];
  41.       for(int i = lf ; i < lf+eq ; i++) ar[l+i] = pivot;
  42.       for(int i = 0 ; i < rg ; i++) ar[l+lf+eq+i] = right[i];
  43.  
  44.       return l+lf;
  45.     }
  46.  
  47.     public static void swap( int i, int j) {
  48.         int temp = ar[i];
  49.         ar[i] = ar[j];
  50.         ar[j] = temp;
  51.     }
  52.     public static void main (String[] args) throws java.lang.Exception {
  53.         //your code here
  54.         Scanner sc = new Scanner(System.in);
  55.         int n = sc.nextInt();
  56.         ar = new int[n];
  57.         for(int i=0; i<n; i++) {
  58.             ar[i] = sc.nextInt();
  59.         }
  60.         quicksort(0,n-1);
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement