Quick Sort - Java
import java.util.Arrays;
public class QuickSort {
private static int numbers[];
public static void main(String[] args) {
numbers = new int[]{4,5,2,3,6,1};
sort(numbers);
System.out.println(Arrays.toString(numbers));
}
public static void sort(int[] numbers){
if(numbers.length == 0 || numbers.length == 1)
return;
int length = numbers.length;
quicksort(0, length -1);
}
public static void quicksort(int low, int high){
int i = low;
int j = high;
int pivot = numbers[low + (high - low)/2];
while(i <= j){
while(numbers[i] < pivot)
i++;
while(numbers[j] > pivot)
j--;
if(i <= j){
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
i++;
j--;
}
if(low < j)
quicksort(low, j);
if(high > i)
quicksort(i, high);
}
}
}
o/p: 1 2 3 4 5 6
public class QuickSort {
private static int numbers[];
public static void main(String[] args) {
numbers = new int[]{4,5,2,3,6,1};
sort(numbers);
System.out.println(Arrays.toString(numbers));
}
public static void sort(int[] numbers){
if(numbers.length == 0 || numbers.length == 1)
return;
int length = numbers.length;
quicksort(0, length -1);
}
public static void quicksort(int low, int high){
int i = low;
int j = high;
int pivot = numbers[low + (high - low)/2];
while(i <= j){
while(numbers[i] < pivot)
i++;
while(numbers[j] > pivot)
j--;
if(i <= j){
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
i++;
j--;
}
if(low < j)
quicksort(low, j);
if(high > i)
quicksort(i, high);
}
}
}
o/p: 1 2 3 4 5 6
Comments
Post a Comment