Example 1: Quicksort java
import java.util.Arrays;
public class QuickSortInJava
{
int partition(int[] arrNumbers, int low, int high)
{
int pivot = arrNumbers[high];
int a = (low - 1);
for(int b = low; b < high; b++)
{
if(arrNumbers[b] < pivot)
{
a++;
int temp = arrNumbers[a];
arrNumbers[a] = arrNumbers[b];
arrNumbers[b] = temp;
}
}
int temp = arrNumbers[a + 1];
arrNumbers[a + 1] = arrNumbers[high];
arrNumbers[high] = temp;
return a + 1;
}
void sort(int[] arrNumbers, int low, int high)
{
if (low < high)
{
int p = partition(arrNumbers, low, high);
sort(arrNumbers, low, p - 1);
sort(arrNumbers, p + 1, high);
}
}
static void displayArray(int[] arrNumbers)
{
int s = arrNumbers.length;
for(int a = 0; a < s; ++a)
System.out.print(arrNumbers[a] + " ");
System.out.println();
}
public static void main(String[] args)
{
int[] arrNumbers = {59, 74, 85, 67, 56, 29, 68, 34};
int s = arrNumbers.length;
QuickSortInJava obj = new QuickSortInJava();
obj.sort(arrNumbers, 0, s - 1);
System.out.println("After sorting array: ");
displayArray(arrNumbers);
}
}
Example 2: quick sort code in java
import java.util.*;
class QuickSort {
int partition(int intArray[], int low, int high) {
int pi = intArray[high];
int i = (low-1);
for (int j=low; j<high; j++) {
if (intArray[j] <= pi) {
i++;
int temp = intArray[i];
intArray[i] = intArray[j];
intArray[j] = temp;
}
}
int temp = intArray[i+1];
intArray[i+1] = intArray[high];
intArray[high] = temp;
return i+1;
}
void quick_sort(int intArray[], int low, int high) {
if (low < high) {
int pi = partition(intArray, low, high);
quick_sort(intArray, low, pi-1);
quick_sort(intArray, pi+1, high);
}
}
}
class QUICK_SORT{
public static void main(String args[]) {
int intArray[] = {3,2,1,6,5,4};
int n = intArray.length;
System.out.println("Original Array: " + Arrays.toString(intArray));
QuickSort obj = new QuickSort();
obj.quick_sort(intArray, 0, n-1);
System.out.println("\nSorted Array: " + Arrays.toString(intArray));
}
}
Example 3: quick sort program in c
#include<stdio.h>
void quicksort(int number[25],int first,int last){
int i, j, pivot, temp;
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j){
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot])
j--;
if(i<j){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
}
int main(){
int i, count, number[25];
printf("How many elements are u going to enter?: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
quicksort(number,0,count-1);
printf("Order of Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0;
}