Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create QuickSort.java #741

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions algorithms/QuickSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
public class QuickSort
{
public static void main(String[] args)
{
// This is unsorted array
Integer[] array = new Integer[] { 12, 13, 24, 10, 3, 6, 90, 70 };

// Let's sort using quick sort
quickSort( array, 0, array.length - 1 );

// Verify sorted array
System.out.println(Arrays.toString(array));
}

public static void quickSort(Integer[] arr, int low, int high)
{
//check for empty or null array
if (arr == null || arr.length == 0){
return;
}

if (low >= high){
return;
}

//Get the pivot element from the middle of the list
int middle = low + (high - low) / 2;
int pivot = arr[middle];

// make left < pivot and right > pivot
int i = low, j = high;
while (i <= j)
{
//Check until all values on left side array are lower than pivot
while (arr[i] < pivot)
{
i++;
}
//Check until all values on left side array are greater than pivot
while (arr[j] > pivot)
{
j--;
}
//Now compare values from both side of lists to see if they need swapping
//After swapping move the iterator on both lists
if (i <= j)
{
swap (arr, i, j);
i++;
j--;
}
}
//Do same operation as above recursively to sort two sub arrays
if (low < j){
quickSort(arr, low, j);
}
if (high > i){
quickSort(arr, i, high);
}
}

public static void swap (Integer array[], int x, int y)
{
int temp = array[x];
array[x] = array[y];
array[y] = temp;
}
}