Quick Sort
import java.util.*;
public class QuickSort
{
public static void main(String args[]) // execution starts from here
{
int arr[] = {10, 7, 8, 3, 4, 1, 5};
int n = arr.length;
Quicksort obj = new QuickSort();
obj.sort(arr, 0, n-1);
printArray(arr);
}
static void printArray(int arr[]) // static method no need to make an object to call this method
{
int i, l;
l = arr.length;
System.out.println(" ");
for(i=0;i<l;i++)
{
System.out.print(arr[i] + " ");
}
}
int partition(int arr[], int low, int high)
{
int pivot, i, j,temp;
pivot = arr[high];
i = low-1;
for(j=low;j<high;j++)
{
if(arr[j]<=pivot)
{
i++;
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
}
}
void sort(int arr[], int low, int high)
{
if(low<high)
{
int pi = partition(arr, low, high);
sort(arr, low, pi-1);
sort(arr, pi+1, high);
}
}
}
public class QuickSort
{
public static void main(String args[]) // execution starts from here
{
int arr[] = {10, 7, 8, 3, 4, 1, 5};
int n = arr.length;
Quicksort obj = new QuickSort();
obj.sort(arr, 0, n-1);
printArray(arr);
}
static void printArray(int arr[]) // static method no need to make an object to call this method
{
int i, l;
l = arr.length;
System.out.println(" ");
for(i=0;i<l;i++)
{
System.out.print(arr[i] + " ");
}
}
int partition(int arr[], int low, int high)
{
int pivot, i, j,temp;
pivot = arr[high];
i = low-1;
for(j=low;j<high;j++)
{
if(arr[j]<=pivot)
{
i++;
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
}
}
void sort(int arr[], int low, int high)
{
if(low<high)
{
int pi = partition(arr, low, high);
sort(arr, low, pi-1);
sort(arr, pi+1, high);
}
}
}
Comments
Post a Comment