#include <stdio.h>
void quicksort(int *a, int left, int right)
{
int i = left, j = right-1;
int tmp;
int pivot = a[right];
while (i <= j) {
while (a[i] < pivot)
i++;
while (j>=left && a[j] >= pivot)
j--;
if (i <= j) {
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
i++;
j--;
}
}
tmp=a[i];
a[i]=a[right];
a[right]=tmp;
if (left < i - 1)
quicksort(a, left, i - 1);
if ((i+1) < right)
quicksort(a, i+1, right);
}
main()
{
int a[100],n,i;
printf("enter n value");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
quicksort(a,0,n-1);
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
Output:
Quick Sort Java Program
import java.util.Scanner;
import java.util.Arrays;
public class MyClass
{
public static void QuickSort(int a[],int start, int end)
{
int i=start,j=end-1,pivot=end;
while(i<=j)
{
while(a[i] < a[pivot] )
i++;
while(j>=start && a[j] >= a[pivot])
j--;
if(i<j)
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
int temp=a[i];
a[i]=a[pivot];
a[pivot]=temp;
if(start < i-1)
QuickSort(a,start,i-1);
if(i+1 < end)
QuickSort(a,i+1,end);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("enter number of elements");
int n = sc.nextInt();
int a[] = new int[n];
System.out.println("enter array elements");
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
QuickSort(a,0,n-1);
System.out.println("Sorted array");
System.out.println(Arrays.toString(a));
}
}
void quicksort(int *a, int left, int right)
{
int i = left, j = right-1;
int tmp;
int pivot = a[right];
while (i <= j) {
while (a[i] < pivot)
i++;
while (j>=left && a[j] >= pivot)
j--;
if (i <= j) {
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
i++;
j--;
}
}
tmp=a[i];
a[i]=a[right];
a[right]=tmp;
if (left < i - 1)
quicksort(a, left, i - 1);
if ((i+1) < right)
quicksort(a, i+1, right);
}
main()
{
int a[100],n,i;
printf("enter n value");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
quicksort(a,0,n-1);
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
Output:
Quick Sort Java Program
import java.util.Scanner;
import java.util.Arrays;
public class MyClass
{
public static void QuickSort(int a[],int start, int end)
{
int i=start,j=end-1,pivot=end;
while(i<=j)
{
while(a[i] < a[pivot] )
i++;
while(j>=start && a[j] >= a[pivot])
j--;
if(i<j)
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
int temp=a[i];
a[i]=a[pivot];
a[pivot]=temp;
if(start < i-1)
QuickSort(a,start,i-1);
if(i+1 < end)
QuickSort(a,i+1,end);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("enter number of elements");
int n = sc.nextInt();
int a[] = new int[n];
System.out.println("enter array elements");
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
QuickSort(a,0,n-1);
System.out.println("Sorted array");
System.out.println(Arrays.toString(a));
}
}