Showing posts with label Quick Sort. Show all posts
Showing posts with label Quick Sort. Show all posts

Saturday, August 30, 2014

Quick Sort

Sorting is one of the basic algorithms any SDET must know,
I'm sharing a popular and efficient Sorting algorithm, for you to add it up your sleeves

public class Quick_Sort {

public static void exchange(int[] arr, int index1, int index2){
int temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
}
public static void Quicksort(int[] arr, int low, int high) {


int i=low;
int j=high;
int pivot = arr[(i+j)/2];

//Divide the array into two parts
while(i<=j){

while(arr[i]<pivot){
i++;
}

while(arr[j]>pivot){
j--;
}

if(i<=j){
exchange(arr,i,j);
i++;
j--;

}

if(low<j){
Quicksort(arr,low, j);
}
if(i<high){
Quicksort(arr, i, high);
}
}

}

public static void printarray(int[] arr){
for(int i=0; i<arr.length; i++){

System.out.print(" "+arr[i]);
}
}

public static void main(String[] args) {

int[] arr = {10, 20, 2, 3, 24, 45, 100};
System.out.println();
System.out.println(" Before Sorting");
printarray(arr);
Quicksort(arr, 0, arr.length-1);
System.out.println();
System.out.println(" After Sorting");
printarray(arr);

}