i am trying to implement quicksort but i am not getting correct results. Here is my code:
public static void quickSort(Comparable[] a, int start, int stop) {
if (start < stop) {
int pivot = partition(a, start ,stop);
System.out.print("Pivot: "+a[pivot]+" Array: ");
printArray(a);
quickSort(a,start,pivot-1);
quickSort(a,pivot+1, stop);
}
}
public static int partition(Comparable[] a, int start, int stop) {
Comparable pivot = a[stop];
int i = start;
int j = stop-1;
while (i < j) {
while( (isLess(a[i], pivot)|| isEqual(a[i], pivot)))
i++;
while((isGreater(a[j], pivot)|| isEqual(a[j], pivot)))
j--;
if(i < j)
swap(a, i,j);
}
swap(a,i, stop);
return i;
}
For input: {51,17,82,10,97,6,23,45,6,73}, i am getting result: 6 6 10 17 23 45 51 73 97 82
For input: {12,9,4,99,120,1,3,10}, i am getting an index out of bounds error. Would appreciate some help in where i am going wrong.
Your two problems are unrelated.
The problem with {51,17,82,10,97,6,23,45,6,73} is — what happens when stop == start + 1? Then i == start == stop - 1 == j, so you never enter the while-loop, so you unconditionally swap(a, i, stop) — even if a[i] was already less than a[stop].
The problem with {12,9,4,99,120,1,3,10} is seemingly that you didn't read the stacktrace. ;-) Assuming you have a decent Java compiler and JVM, it should have given you the exact line-number and problematic index, so you would have seen that the problem is in this line:
while((isGreater(a[j], pivot)|| isEqual(a[j], pivot)))
once j gets to -1. (This will happen if pivot is the very least value in the range of interest.) You just need to add a check for that:
while(j > start && (isGreater(a[j], pivot)|| isEqual(a[j], pivot)))
(and, for that matter, for the corresponding case of i:
while(i < stop && (isLess(a[i], pivot)|| isEqual(a[i], pivot)))
)
. . . and you need to learn how to debug your code. :-)
I recommend you Algorithms: Design and Analysis, very good internet course from Stanford. After this course you will write such codes more easily. It is a bit enhanced version, pivot is chosen as a median of three. Note that you don't have to write your own printArray() function. In Java you can do it with System.out.println(Arrays.toString(numbers)). Also you can observe how to call quickSort() in more elegant way, with only one argument, using method overloading.
public class QuickSort
{
public static void main(String[] args)
{
int numbers[] =
{ 51, 17, 82, 10, 97, 6, 23, 45, 6, 73 };
quickSort(numbers);
System.out.println(Arrays.toString(numbers));
}
public static void quickSort(int[] array)
{
quickSort(array, 0, array.length - 1);
}
private static void quickSort(int[] array, int left, int right)
{
if (left >= right)
{
return;
}
int pivot = choosePivot(array, left, right);
pivot = partition(array, pivot, left, right);
quickSort(array, left, pivot - 1);
quickSort(array, pivot + 1, right);
}
private static int partition(int[] array, int pivot, int left, int right)
{
swap(array, pivot, left);
pivot = left;
int i = left + 1;
for (int j = left + 1; j <= right; j++)
{
if (array[j] < array[pivot])
{
swap(array, j, i);
i++;
}
}
swap(array, pivot, i - 1);
return i - 1;
}
private static void swap(int[] array, int j, int i)
{
int temp = array[j];
array[j] = array[i];
array[i] = temp;
}
private static int choosePivot(int[] array, int left, int right)
{
return medianOfThree(array, left, (left + right) / 2, right);
// return right;
}
private static int medianOfThree(int[] array, int aIndex, int bIndex, int cIndex)
{
int a = array[aIndex];
int b = array[bIndex];
int c = array[cIndex];
int largeIndex, smallIndex;
if (a > b)
{
largeIndex = aIndex;
smallIndex = bIndex;
}
else
{
largeIndex = bIndex;
smallIndex = aIndex;
}
if (c > array[largeIndex])
{
return largeIndex;
}
else
{
if (c < array[smallIndex])
{
return smallIndex;
}
else
{
return cIndex;
}
}
}
}
Related
I'm trying to code the quick sort algorithm using java. My problem is, that i cannot call the sort method. This is my code:
public class quickSort
{
int partition(int a[], int left, int right)
{
int i= left, j= right, temp;
int pivot=a[j];
//System.out.println(pivot+"pivot");
while(i<=j)
{
while(a[i]<pivot)
i++;
while(a[j-1]>pivot)
j++;
if(i<j)
{
temp=a[i];
a[i]=a[j-1];
a[j-1]=temp;
System.out.println(a[i] +"i");
System.out.println(a[j-1] +"j");
i++;
j--;
}
}
System.out.println(i);
System.out.println(j);
return i;
}
int[] sort(int[] numbers, int left, int right)
{
int x = partition(numbers, left, right);
System.out.println(x +"Qi");
if(left < right)
sort(numbers, left, x-1);
sort(numbers, x+1, right);
return numbers;
}
public static void main(String[] args)
{
quickSort q= new quickSort();
int[] numbers = {2,6,4,9,7,0,1,3,5};
int left = 0, right=numbers.length-1;
q.sort(numbers, left, right);
}
}
problem:
sort(numbers, left, x-1);
sort(numbers, x+1, right);
this recursion is not getting executed
It also results in an out of bounds exception, when i try to code in the partition method.
This is a screenshot of the output I m using it just to display the output and show the IDE I used to execute :
https://drive.google.com/file/d/1j6lHuEONZkO_Dr3ZszoPKh4bNXZgkgbT/view?usp=sharing.
The current code produces in the partition-method either an endless loop or an ArrayIndexOutOfBoundsException depending on your choosen numbers-array. A possible fix is e.g.:
private int partition(int a[], int left, int right) {
int i = left, j = right, temp;
int pivot = a[j];
while (i <= j) {
if (a[i] > pivot) {
temp = a[i];
for (int k = i; k < right; k++) { // remove a[i] and move all elements...
a[k] = a[k + 1]; // ...following a[i] to the left
}
j--; // decrement pivot's index
a[right] = temp; // move a[i] to the right end
} else {
i++;
}
}
return j; // return pivot's modified index
}
Furthermore, in the sort-method you have to ensure for both recursive sort-calls that the left boundary is smaller than the right boundary, e.g.:
private int[] sort(int[] numbers, int left, int right) {
int x = partition(numbers, left, right);
if (left < right) { // left boundary smaller than right one
sort(numbers, left, x - 1);
sort(numbers, x + 1, right);
}
return numbers;
}
I am new to Java and I am trying to implement QuickSort.
Here is my script below.
public class QuickSort {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[] ={5,6,7,4,1,3};
QuickSort qs = new QuickSort();
qs.quickSort(a,0,a.length-1);
for(int i=0;i<a.length;i++) {
System.out.println(a[i]);
}
}
public void quickSort(int[] a,int left, int length) {
if(left >= length) return;
int index = partition(a,left,length);
if(left < index) {
quickSort(a,left,index-1);
}
else {
quickSort(a,index,length);
}
}
private int partition(int[] a,int l, int length) {
// TODO Auto-generated method stub
int left = l;
int right = length;
int pivot = a[(left+right)/2];
while(left <= right) {
while(left < length && a[left] < pivot) {
left++;
}
while(right >= 0 && a[right] > pivot) {
right--;
}
if(left <= right) {
int temp = a[left];
a[left]=a[right];
a[right]=temp;
left++;
right--;
}
}
return left;
}
}
When , I print the solution I get the following order-
[1,3,6,4,5,7]
I am unable to figure out the error, can anyone please help me fix this problem.
just change this
if(left < index) {
quickSort(a,left,index-1);
}
else {
quickSort(a,index,length);
}
to this
quickSort(a,left,index-1);
quickSort(a,index+1,length);
Since you need to sort array recursively on every partition of the array!
Quicksort breaks the array into two smaller arrays, on either side of the pivot. This means that each call to quicksort should result in two more calls to quicksort. Your code currently calls quicksort recursively, but only on one half.
Quicksort(array)
pick a pivot
Arrays left, right
For each value in array
If value < pivot
Append to left array
Else
Append to right array
Quicksort(left)
Quicksort(right)
Return join(left, right)
Try the following code:
import java.util.ArrayList;
public class MyQuickSort {
/**
* #param args
*/
public static void main(String[] args) {
//int[] a = { 1, 23, 45, 2, 8, 134, 9, 4, 2000 };
int a[]={23,44,1,2009,2,88,123,7,999,1040,88};
quickSort(a, 0, a.length - 1);
System.out.println(a);
ArrayList al = new ArrayList();
}
public static void quickSort(int[] a, int p, int r)
{
if(p<r)
{
int q=partition(a,p,r);
quickSort(a,p,q);
quickSort(a,q+1,r);
}
}
private static int partition(int[] a, int p, int r) {
int x = a[p];
int i = p-1 ;
int j = r+1 ;
while (true) {
i++;
while ( i< r && a[i] < x)
i++;
j--;
while (j>p && a[j] > x)
j--;
if (i < j)
swap(a, i, j);
else
return j;
}
}
private static void swap(int[] a, int i, int j) {
// TODO Auto-generated method stub
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
Taken from here
Below are the edited code you can replace it,
public void quickSort(int[] a,int left, int length) {
if(left >= length) return;
int index = partition(a,left,length);
if (left < index)
quickSort(a, left, index); // left subarray
if (length > index + 1)
quickSort(a, index + 1, length);
}
private int partition(int[] arr,int l, int length) {
// TODO Auto-generated method stub
int pivot = arr[(l + length)/2];
int left = l - 1; // index going left to right
int right = length + 1; // index going right to left
while (true) {
do {
left++;
} while (arr[left] < pivot);
do {
right--;
} while (arr[right] > pivot);
if (left < right){
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
else
return right; // index of last element in the left subarray
}
}
Quicksort is a divide and conquer algorithm. It first divides a large list into two smaller sub-lists and then recursively sort the two sub-lists. If we want to sort an array without any extra space, quicksort is a good option. On average, time complexity is O(n log(n)).
The basic step of sorting an array are as follows:
Select a pivot, normally the middle one
From both ends, swap elements and make all elements on the left less than the pivot and all elements on the right greater than the pivot
Recursively sort left part and right part
Arrays.sort() method in Java use quicksort to sort array of primitives e.g. array of integers or float and uses Mergesort to sot objects e.g. array of String.
I tried and wrote a code for Quicksort with middle element as pivot.
I was successful in writing one.
But Pivot has the property that:
Elements on its left are lesser than pivot and greater on its right.
I was not able to achieve this in my following code.
private static void QuickSortAlgorithm(int[] a, int i, int n)
{
if(i<n)
{
int part = partition(a,i,n);
QuickSortAlgorithm(a, i, part-1);
QuickSortAlgorithm(a, part, n);
}
}
private static int partition(int[] a, int i, int n)
{
int pivot = (i+n)/2;
int left = i;
int right = n;
while(left<=right)
{
while(a[left]<a[pivot]){
left++;
}
while(a[right]>a[pivot])
{
right--;
}
if(left<=right)
{
swap(a,left,right);
left++;
right--;
}
}
return left;
}
Main Method:
int a[]={5,7,3,9,1};
int n = a.length;
QuickSortAlgorithm(a,0,n-1);
System.out.println(Arrays.toString(a));
My doubt is:
I am sending left as my partitioned index.
But, when I am recursively calling QuickSortAlgorithm()
I am sending i to part-1 and part to n;
What should I send as partition index so that
I could call something like this: So that pivot property is satisfied?
QuickSortAlgorithm(a, i, part-1);
QuickSortAlgorithm(a, part+1, n);
Thank you:)
you have to send pivot value in first stack call inclusive and pivot+1 as lower index for second stack call.
You also have to put value of left as i+1 then your code will give an correct output
You have to change the return value to left+1 in partition method.
Try this program:
import java.io.*;
public class QuickSort {
public int partion(int[] a, int l, int h) {
int middle = (h+l)/2;
//System.out.println(middle);
int pivot = a[middle];
int i = l;
int j = h;
while (i <= j) {
while (a[i] < pivot) i++;
while (a[j] > pivot) j--;
if (i <= j) {
swap(a, i, j);
i++;
j--;
}
}
// swap(a,i,j);
System.out.println((i+j)/2);
return i-1;
}
public void quick(int[] a, int l, int h) {
if (l<h) {
int pi = partion(a, l, h);
System.out.println(pi);
if (l < pi - 1)
quick(a, l, pi+1);
if (pi < h)
quick(a, pi+1, h);
}
}
public void swap(int[] a, int l, int h){
int temp=a[l];
a[l]=a[h];
a[h]=temp;
}
public static void main(String[] args) {
int[] a = {10,80,30,90,40,50,70};
int l=0;
int h=a.length-1;
QuickSort q =new QuickSort();
q.quick(a,0,h);
System.out.println(" Sorted Array : ");
for(int e :a){
System.out.print(e+" , ");
}
}
}
You can choose the leftmost element in the array or you can choose any random element to be your pivot.
Check out the wikipedia page on quicksort for more details about choosing pivot
I've been banging my head on the table on this one.
I need to create an n sized array that is optimized for QuickSort Partition. It will be used to demonstrate the growth of QuickSort's best case. I know that for best case, QuickSort must select a pivot that divides the array in half for every recursive call.
I cannot think of a way to create an n-sized optimized array to test. Any help would be greatly appreciated.
Here is the algorithm in Java.
public class QuickSort {
private int length;
private void quickSort(int[] a, int p, int r) {
if (p < r) {
int q = partition(a, p, r);
quickSort(a, p, q - 1);
quickSort(a, q + 1, r);
}
}
private int partition(int[] a, int p, int r) {
int x = a[r];
int i = p - 1;
for (int j = p; j < r; j++) {
if (a[j] <= x) {
i++;
exchange(a, i, j);
}
}
exchange(a, i + 1, r);
return i + 1;
}
public void exchange(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
QuickSort(int[] a) {
if (a == null || a.length == 0) {
return;
}
length = a.length;
quickSort(a, 0, length - 1);
}
}
I know this is an old question, but I had the same question and finally developed a solution. I'm not a Java programmer, so don't blame me for Java code issues, please. I assumed that the quicksort algorithm always takes the first item as a pivot when partitioning.
public class QuickSortBestCase
{
public static void generate(int[] arr, int begin, int end)
{
int count = end - begin;
if(count < 3)
return;
//Find a middle element index
//This will be the pivot element for the part of the array [begin; end)
int middle = begin + (count - 1) / 2;
//Make the left part best-case first: [begin; middle)
generate(arr, begin, middle);
//Swap the pivot and the start element
swap(arr, begin, middle);
//Make the right part best-case, too: (middle; end)
generate(arr, ++middle, end);
}
private static void swap(int[] arr, int i, int j)
{
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
private static void fillArray(int[] arr)
{
for(int i = 0; i != arr.length; ++i)
arr[i] = i + 1;
}
private static void printArray(int[] arr)
{
for(int item : arr)
System.out.print(item + " ");
}
public static void main(String[] args)
{
if(args.length == 0)
return;
int intCount = Integer.parseInt(args[0]);
int[] arr = new int[intCount];
//We basically do what quicksort does in reverse
//1. Fill the array with sorted values from 1 to arr.length
fillArray(arr);
//2. Recursively generate the best-case array for quicksort
generate(arr, 0, arr.length);
printArray(arr);
}
}
This program produces the same output for the array of 15 items, as described here: An example of Best Case Scenario for Quick Sort. And in case someone needs a solution in C++:
template<typename RandomIterator,
typename Compare = std::less<typename RandomIterator::value_type>>
void generate_quicksort_best_case_sorted(RandomIterator begin, RandomIterator end)
{
auto count = std::distance(begin, end);
if (count < 3)
return;
auto middle_index = (count - 1) / 2;
auto middle = begin + middle_index;
//Make the left part best-case first
generate_quicksort_best_case_sorted(begin, middle);
//Swap the pivot and the start element
std::iter_swap(begin, middle);
//Make the right part best-case, too
generate_quicksort_best_case_sorted(++middle, end);
}
template<typename RandomIterator,
typename Compare = std::less<typename RandomIterator::value_type>>
void generate_quicksort_best_case(RandomIterator begin, RandomIterator end)
{
{
auto current = begin;
RandomIterator::value_type value = 1;
while (current != end)
*current++ = value++;
}
generate_quicksort_best_case_sorted(begin, end);
}
I'm using this simple implementation. I just want to count the comparisons. Below the code actually works.
The list is [3, 9, 8, 4, 6, 10, 2, 5, 7, 1].
The answer for comparison count is 25 but I'm getting 30. I can't figure out why. What causes this code to do "more work" than it is supposed to? Thanks in advance!
public void sort(int[] values){
int length = values.length;
if(values == null || length == 0){
return;
}
quicksort(values, 0, length-1);
}
private int partition(int arr[], int left, int right){
int i = left+1;
int pivot = arr[left];
for(int j=(left+1); j<=right; j++){
comparisonCount++;
if(arr[j] < pivot){
swap(arr,i,j);
i++;
}
}
swap(arr,left, i-1);
return i;
}
private void quicksort(int arr[], int left, int right) {
int index = partition(arr, left, right);
if (left < index - 1){
quicksort(arr, left, index-1);
}
if (index < right){
quicksort(arr, index, right);
}
}
private void swap(int[] arr, int i, int j){
int tmp;
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
Well, I appear to have found where the discrepancy is coming from:
quicksort(values, 0, length - 1); // initial call in sort()
for (int j = (left + 1); j <= right; j++) { // loop in partition()
Versus
quicksort(values, 0, length); // initial call in sort()
for (int j = (left + 1); j < right; j++) { // loop in partition()
First one gives 30 comparisons, second gives 25.
Why this is the case? I suspect it has something to do with how the loop invariant is set up. My guess is that you're comparing some pivot multiple times due to the way the bounds were set up. I'm too brain-dead to figure out the exact bounds, so I'll try to remember to come back once I get that figured out.