Iterative approach:-
public class QuickSort {
public static void main(String args[]){
int numbers[] = {-1,10,8,4,12};
int number = numbers.length;
}
private static void sort(int[] numbers,int number){
int low =0;
int i =0;
int high = number-1;
while(low<high){
int pivot = numbers[low + (high-low)/2];
while(numbers[low]<pivot){
low++;
}
while(numbers[low]>pivot){
high--;
}
if(low<=high){
exchange(low,high,numbers);
low++;
high--;
}
}
if(i<high){
}
}
private static void exchange(int low, int high,int[] numbers) {
// TODO Auto-generated method stub
int temp = numbers[low];
numbers[low] = numbers[high];
numbers[high] = numbers[temp];
}
}
Recursive approach :-
public class QuickSort {
public static void main(String[] args) {
int[] xyz = { 5, 2, 4, 8, 1, 5, 3 };
if (xyz != null && xyz.length > 0) {
quickSort(xyz, 0, xyz.length - 1);
} else {
System.out.println("Empty array");
}
printArray(xyz);
}
private static void printArray(int[] xyz) {
for (int i = 0; i < xyz.length; i++) {
System.out.println(xyz[i]);
}
}
private static void quickSort(int[] xyz, int low, int high) {
if (low < high) {
int pi = calculatePartion(xyz, low, high);
quickSort(xyz, low, pi - 1);
quickSort(xyz, pi + 1, high);
}
}
private static int calculatePartion(int[] xyz, int low, int high) {
int pivot = xyz[high];
int i = low;
for (int j = low; j < high; j++) {
if (xyz[j] <= pivot) {
swap(xyz, j, i);
i = i + 1;
}
}
swap(xyz, i, high);
return i;
}
private static void swap(int[] xyz, int i, int placeHodler) {
int temp = xyz[placeHodler];
xyz[placeHodler] = xyz[i];
xyz[i] = temp;
}
}
No comments:
Post a Comment