Quick Sort program in java

 //Implementation of Quick sort by using recursive approach

import java.util.Scanner;

import java.util.Arrays;


class SortQuickPractice

{

public static void main(String args[])

{

Scanner s=new Scanner(System.in);

System.out.println("Enter a positive Integer number :");

int length=s.nextInt();

int arr[]=new int[length];

for(int i=0; i<arr.length; i++)

{

arr[i]=s.nextInt();

}

SortQuickPractice obj=new SortQuickPractice();

obj.sort(arr,0,arr.length-1);

System.out.println("Sorted Data elements :"+Arrays.toString(arr));

}

private void sort(int arr[], int lower, int upper)

{

if(lower>upper)

{

return;

}

else

{

int pivotIndex=partition(arr,lower,upper);

sort(arr,lower,pivotIndex-1);//sort for left 

sort(arr,pivotIndex+1,upper);//sort for right sub partition

}

}

private int partition(int arr[], int lower, int upper)

{

int pivot=arr[lower];

int p=lower;

int q=upper;

while(p<q)

{

while(p<q && pivot>arr[p])

{

p=p+1;

}

while(q>p && pivot<arr[q])

{

q=q-1;

}

if(p<q)

{

int temp=arr[p];

arr[p]=arr[q];

arr[q]=temp;

}

}

pivot=arr[q];

return q;

}

}

Expected Output :



Post a Comment

0 Comments