Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Why is my unit test failing for quicksort, in Java? public class QuickSort { static void swap(int[] A, int i, int j) { int tmp

Why is my unit test failing for quicksort, in Java?

public class QuickSort { static void swap(int[] A, int i, int j) { int tmp = A[i]; A[i] = A[j]; A[j] = tmp; } static final int LIMIT = 15; static int partition(int[] a, int left, int right){ int center = (left + right) / 2; if(a[center] < (a[left])) swap(a,left,center); if(a[right-1] < a[left]) swap(a,left,right); if(a[right-1] < a[center]) swap(a,center,right); swap(a,center,right - 1); return a[right - 1]; } static void quicksort(int[] a, int left, int right){ if(left + LIMIT <= right){ int pivot = partition(a,left,right); int i = left; int j = right - 1; for(;;){ while(a[++i] < pivot){} while(a[--j] > pivot){} if(i < j) swap(a,i,j); else break; } swap(a,i,right - 1); quicksort(a,left,i-1); quicksort(a,i+1,right); } else{ insertionSort(a); } } public static void insertionSort(int[] a){ int j; for(int p = 1; p < a.length; p++){ int tmp = a[p]; for(j = p; j > 0 && tmp < a[j-1]; j--) a[j] = a[j-1]; a[j] = tmp; } } } 

This test fails:

public void smalltest() throws Exception { int[] Arr_orig = {3,9,8,2,4,6,7,5}; int[] Arr = Arr_orig.clone(); int pivot = QuickSort.partition(Arr, 0, Arr.length); for (int i = 0; i != pivot; ++i) assertTrue(Arr[i] <= Arr[pivot]); //fails! for (int i = pivot + 1; i != Arr.length; ++i) assertTrue(Arr[pivot] < Arr[i]); }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Oracle Autonomous Database In Enterprise Architecture

Authors: Bal Mukund Sharma, Krishnakumar KM, Rashmi Panda

1st Edition

1801072248, 978-1801072243

More Books

Students also viewed these Databases questions