Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.lang.*;
- import java.io.*;
- public class Main {
- public static int[] ar;
- public static void quicksort( int l, int h) {
- // System.out.println(l + " " + h);
- if(l<h) {
- int pi = partition(l,h);
- quicksort(l,pi-1);
- quicksort(pi+1,h);
- // if(l==4 && h==6)
- for(int j=l; j<=h; j++) {
- System.out.print(ar[j]+" ");
- }
- System.out.println();
- }
- }
- public static int partition( int l, int h) {
- int[] left,right;
- int pivot = ar[l];
- int lf = 0,rg = 0,eq = 1;
- for(int i = l+1 ; i <= h ; i++){
- if(ar[i] < pivot) lf++;
- else if(ar[i] > pivot) rg++;
- else eq++;
- }
- left = new int[lf];
- int j = 0,k=0;
- right = new int[rg];
- for(int i = l+1 ; i <= h ; i++){
- if(ar[i] < pivot) left[j++] = ar[i];
- else if(ar[i] > pivot ) right[k++] = ar[i];
- }
- for(int i = 0 ; i < lf ; i++) ar[l+i] = left[i];
- for(int i = lf ; i < lf+eq ; i++) ar[l+i] = pivot;
- for(int i = 0 ; i < rg ; i++) ar[l+lf+eq+i] = right[i];
- return l+lf;
- }
- public static void swap( int i, int j) {
- int temp = ar[i];
- ar[i] = ar[j];
- ar[j] = temp;
- }
- public static void main (String[] args) throws java.lang.Exception {
- //your code here
- Scanner sc = new Scanner(System.in);
- int n = sc.nextInt();
- ar = new int[n];
- for(int i=0; i<n; i++) {
- ar[i] = sc.nextInt();
- }
- quicksort(0,n-1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement