how to count Quicksort comparisons accurately - java

I'm trying to make a program where I count the amount of comparisons quicksort makes but its not 100% accurate. how would I make this comparison counter accurate?
The quicksort takes in an array of n random integers.
Code I have so far:
public int QuickSort(int[] list, int from, int to) {
int icount = 0;
if (from >= to) {
return icount;
}
int p = from;
int i = from;
int j = to;
while (i <= j) {
if (list[i] <= list[p]) {
i++;
icount++;
} else if (list[j] >= list[p]) {
j--;
icount++;
} else {
swap(list, i, j);
i++;
j--;
icount++;
}
}
if (p < j) { // place the pivot in its correct position
swap(list, j, p);
p = j;
icount++;
} else if (p > i) {
swap(list, i, p);
p = i;
icount++;
}
icount += QuickSort(list, from, p - 1);
icount += QuickSort(list, p + 1, to);
return icount;
}
Is there anything wrong with the current code? or is it not possible to be completely accurate with random integers?

Related

Trying to implement merge sort with some modifications

I am trying to implement merge sort algorithm with some optimization like using temp storage only once and avoiding the copy till the last.Everything is okay and many test files are passing except some.The thing that is happening here is with unsorted array,the algorithm is showing some problems.I have written print statements in my code trying to reach the problem,but unable to do so.As many tests are passing,i believe there is nothing major wrong in the program,just it misses something.
I have tried to implement the program and it is successful in many ways,just 3 cases doesn't pass.But,the main problem i am facing is that test case Mergesort_two() doesn't pass because its simple .It's just calling two numbers and asserting in sorted form,but my program is denying it.I believe its a minor error which i am unable to figure out.
public static void mergesort(int[] input, int[] temp,
int start, int end,
boolean intoTemp) {
if (start == end) {
return;
}
if ((start + 1) == end) {
if (intoTemp == true) {
temp[start] = input[start];
return;
}
}
if (start < end) {
if (intoTemp == false) {
intoTemp = true;
int mid = (start + end)/2;
mergesort(input, temp, start, mid, intoTemp);
mergesort(input, temp, mid, end, intoTemp);
merge(input, temp, start, mid, end);
System.out.println("Input Array: " + Arrays.toString(input) +
" Temp: " + Arrays.toString(temp) + " intoTemp: " +
intoTemp + "Start Mid End: " + start + " " + mid + " " + end);
}
else if(intoTemp == true) {
intoTemp = false;
int mid = (start + end)/2;
mergesort(input, temp, start, mid, intoTemp);
mergesort(input, temp, mid, end, intoTemp);
merge(temp, input, start, mid, end);
System.out.println("Input Array: " + Arrays.toString(input) +
" Temp: " + Arrays.toString(temp) + " intoTemp: " +
intoTemp + "Start Mid End: " + start + " " + mid + " " + end);
}
}
if (start == 0 && end == input.length) {
System.arraycopy(temp, 0, input, 0, input.length);
}
}
/** Merges input[start...mid-1] with input[mid...end-1] into
* output[start...end-1]. The input array should not be modified at
* all, and only start...end-1 of the output array should be changed.
*
* #param input Input array
* #param output Output array
* #param start Starting index
* #param mid Midpoint index
* #param end Ending index+1
*/
public static void merge(int[] input, int[] output,
int start, int mid, int end) {
if (input == null || (start == mid && mid == end)) {
return;
}
int i = start;
int j = mid - 1;
int k = mid;
int index = start;
while (i <= j && k < end) {
if (input[i] <= input[k]) {
output[index] = input[i];
i++;
index++;
}
if (input[i] > input[k]) {
output[index] = input[i];
k++;
index++;
}
}
while (i <= j) {
output[index] = input[i];
index++;
i++;
}
while (k < end) {
output[index] = input[k];
index++;
k++;
}
}
}
////// Test Cases
#Test
public void testMergesort_Two() {
System.out.println("mergesort one element");
int[] array = new int[2];
// Already sorted
array[0] = 10; array[1] = 13;
CSSE240_Assign4.mergesort(array);
assertEquals(array[0], 10);
assertEquals(array[1], 13);
// Unsorted
array[0] = 3; array[1] = -4;
CSSE240_Assign4.mergesort(array);
assertEquals(array[0], -4);
assertEquals(array[1], 3);
}
#Test
public void testMergesort_Large() {
System.out.println("mergesort one large");
Random rng = new Random();
for(int s = 3; s < 20; ++s) {
int[] array = new int[s];
int[] orig = new int[s];
// Fill with random values.
for(int i = 0; i < s; ++i) {
array[i] = rng.nextInt();
orig[i] = array[i];
}
CSSE240_Assign4.mergesort(array);
Arrays.sort(orig);
// Make sure both arrays agree
for(int i = 0; i < s; ++i)
assertEquals(orig[i], array[i]);
}
}
#Test
public void testMergeInterleaved() {
// Various cases where the left/right halves are interleaved. We test
// this by picking a modulo m and moving all the elements where
// e % m < m/2 to the right side.
System.out.println("merge reverse sorted");
for(int s = 3; s < 20; ++s) {
int[] array = new int[s];
int mid = 0;
// Move the elements of the array around into the two halves.
for(int m = 2; m < 5; ++m) {
// Populate the array with 0...s-1
for (int i = 0; i < s; ++i) {
array[i] = i;
}
int[] left = new int[s];
int[] right = new int[s];
int lc = 0, rc = 0;
for(int i = 0; i < s; ++i)
if(array[i] % m < m/2)
right[rc++] = array[i];
else
left[lc++] = array[i];
// Copy back into the array
int j = 0;
for(int i = 0; i < lc; ++i)
array[j++] = left[i];
for(int i = 0; i < rc; ++i)
array[j++] = right[i];
mid = lc; // Midpoint
int[] output = new int[s];
Arrays.fill(output, -1);
// TODO: check different endpoints...
CSSE240_Assign4.merge(array, output, 0, mid, s);
for(int i = 0; i < s; ++i)
assertEquals(output[i], i);
}
}
}
testMergesort_Two Failed : expected <-4> but was <3>
testMergeInterleaved Failed: expected <0> but was <1>
testMergeSort_Large Failed : expected:<-1131373963> but was:<-2038582366>
Changes noted in comments.
public static void mergesort(int[] input, int[] temp,
int start, int end,
boolean intoTemp) {
if (start == end) {
return;
}
if ((start + 1) == end) {
if (intoTemp == true) {
temp[start] = input[start];
return;
}
}
if (intoTemp == false) {
intoTemp = true;
int mid = (start + end)/2;
mergesort(input, temp, start, mid, intoTemp);
mergesort(input, temp, mid, end, intoTemp);
merge(temp, input, start, mid, end);
} else {
intoTemp = false;
int mid = (start + end)/2;
mergesort(input, temp, start, mid, intoTemp);
mergesort(input, temp, mid, end, intoTemp);
merge(input, temp, start, mid, end);
}
}
public static void merge(int[] input, int[] output,
int start, int mid, int end) {
int i = start;
int j = mid; // using j instead of k
// and mid instead of j
int index = start;
while (i < mid && j < end) { // using mid
if (input[i] <= input[j]) {
output[index] = input[i];
i++;
index++;
} else { // change
output[index] = input[j]; // was input[i]
j++;
index++;
}
}
while (i < mid) { // using mid
output[index] = input[i];
i++; // changed order for consistency
index++;
}
while (j < end) {
output[index] = input[j];
j++; // changed order for consistency
index++;
}
}

Making a binary search function

I am working on a homework task where I am supposed to make a function that will do a binary insertion sort, but my function does not seem to work properly.
Here I have tried to combine a binary search function with a insertion sort function (it is specified in the homework task that it needs to be in the form of a function: insertionSort(int[] array, int lo, int hi))
public static void insertionSort(int[] array, int lo, int hi){
int mid;
int pos;
for (int i = 1; i < array.length; i++) {
int x= array[i];
while (lo < hi) {
mid = lo + (hi -lo)/2;
if (x == array[mid]) {
pos = mid;
}
if (x > array[mid]) {
lo = mid+1;
}
else if (x < array[mid]) {
hi = mid-1;
}
}
pos = lo;
for (int j = i; j > pos; j--) {
array[j] = array[j-1];
}
array[pos] = x;
}
}
If I try to run it with the list {2,5,1,8,3}, the output will be
2 5 1 3 1 (if lo < hi and if lo > hi)
2 5 3 8 5 (if lo==hi)
What I am expecting though, is a sorted list...
Any idea of what I am doing wrong?
Just to give you a possible idea:
public static void insertionSort(int[] array) {
if (array.length <= 1) {
return;
}
// Start with an initially sorted part.
int loSorted = array.length - 1;
//int hiSorted = array.length;
while (loSorted > 0) {
// Take one from the array
int x = array[0];
// Where in the sorted part to insert?
int insertI = insertPosition(array, loSorted);
// Insert x at insertI
...
--loSorted;
}
}
whenever I need binary search, my function looks the following way:
public static void binarySearch(int arr[], int first, int last, int key){
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < key ){
first = mid + 1;
}else if ( arr[mid] == key ){
System.out.println("Element is found at index: " + mid);
break;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){
System.out.println("Element is not found!");
}
}
In your main method the call looks like:
public static void main(String[] args) {
int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
binarySearch(arr,0,last,key);
}
I hope I was able to help you!
Thank you for your input. I changed the function a little bit, and it seems to be working now
` public static void insertionSort(int[] array, int lo, int hi){
int mid;
int pos;
for (int i = 1; i < array.length; i++) {
int j = i -1;
int x = array[i];
while (lo <= hi) {
mid = lo + (hi -lo)/2;
if (x == array[mid]) {
pos = mid;
break;
}
if (x > array[mid]) {
lo = mid+1;
}
else if (x < array[mid]) {
hi = mid-1;
}
}
while (j >= 0 && array[j] > x) {
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = x;
}
}
the problem seemed to lay in the last part, where I was trying to move the elements into their right positions. The function is probably not perfect tho, so constructive criticism is welcome :)

Quicksort with duplicate values

I have this java code for QuickSort that works if there are no duplicates, however if there are any duplicates, the QuickSort fails. For example, if I want to QuickSort {5,3,3,1,7} my code will output {1,3,3,7,5}, and I can't seem to figure out why this is the case.
public static void quickSort(Integer[] nums) {
quickSort(nums, 0, nums.length-1);
}
private static void quickSort(Integer[] ary, int lo, int hi) {
//pick num # lo to be pivot
int pivot = lo;
int i = lo+1;
int j = hi;
if( lo==hi) {
return;
}
while(i <j) {
if(ary[i].compareTo(ary[pivot]) <=0 ) {
i++;
}
else if(ary[j].compareTo(ary[pivot]) >=0 ) {
j--;
}
else {
int temp = ary[i];
ary[i] = ary[j];
ary[j] = temp;
}
}
if(i == hi && j == hi) {
if(ary[pivot].compareTo(hi) > 0) {
int temp = ary[pivot];
ary[pivot] = ary[hi];
ary[hi] = temp;
pivot = hi;
}
else {
int temp1 = ary[pivot];
ary[pivot] = ary[i-1];
ary[i-1] = temp1;
pivot = i-1;
}
}
if(lo < pivot -1) {
quickSort(ary, lo, pivot-1);
}
if(pivot +1 < hi) {
quickSort(ary, pivot+1, hi);
}
}
If anyone could tell me what I'm doing wrong, that would be greatly appreciated!
Hi i have modified your code, please check corresponding comments
private static void quickSort(Integer[] ary, int lo, int hi) {
//pick num # lo to be pivot
int pivot = lo;
int i = lo+1;
int j = hi;
if( lo==hi) {
return;
}
//while(i <j) {
for(;;){//change from while to infinite for
while(ary[i].compareTo(ary[pivot]) <=0 && i<hi ) {//changed from if to while with boundary conditions
i++;
}
while(ary[j].compareTo(ary[pivot]) >0 && j>lo) { //change from if to while with boundary conditions and it is not >=0 only >
j--;
}
if(i<j){ //changed from else to if
int temp = ary[i];
ary[i] = ary[j];
ary[j] = temp;
}else{//added else block
break;
}
}
//you didn't handled i>j condition properly i.e when i>j you need to swap pivot and i-1
int temp1 = ary[pivot];
ary[pivot] = ary[i-1];
ary[i-1] = temp1;
pivot = i-1;
//Not required
/*if(i == hi && j == hi) {
if(ary[pivot].compareTo(hi) > 0) {
int temp = ary[pivot];
ary[pivot] = ary[hi];
ary[hi] = temp;
pivot = hi;
}
else {
int temp1 = ary[pivot];
ary[pivot] = ary[i-1];
ary[i-1] = temp1;
pivot = i-1;
}
}*/
if(lo < pivot -1) {
quickSort(ary, lo, pivot-1);
}
if(pivot +1 < hi) {
quickSort(ary, pivot+1, hi);
}
}
Thanks
if you want to quicksort use the algorithm from this site.
Quicksort
It works for me and the explanation is quite good I think.

Sorting and Binary search using Java

I was asked to sort and search an array. The sorting the array was simple and my code worked but then whenever I try to call the binary search method it works for the first element in the array but gives me "-1" as a result
My full code is as follows:
public static void main(String[] args) {
int[] array = new int[5];
array[0] = 50;
array[1] = 40;
array[2] = 10;
array[3] = 20;
array[4] = 100;
sort(array, (array.length - 1));
for (int x = 0; x < array.length; x++) {
System.out.println(" " + array[x]);
}
System.out.println("");
System.out.println("Binary search (R): " + rBsearch(array, 0, (array.length), 20));
}
public static void sort(int[] a, int last) {
if (last > 0) {
int max = findMax(a, last);
swap(a, last, max);
sort(a, last - 1);
}
}
public static int rBsearch(int[] L, int low, int high, int k) {
int mid = (low + high) / 2;
if (low > high) {
return -1;
} else if (L[mid] == k) {
return mid;
} else if (L[mid] < k) {
return rBsearch(L, k, mid + 1, high);
} else {
return rBsearch(L, k, low, mid - 1);
}
}
public static int findMax(int[] arr, int last) {
int max = 0;
for (int i = 0; i <= last; i++) {
if (arr[i] > arr[max]) {
max = i;
}
}
return max;
}
public static void swap(int[] arr, int last, int max) {
int temp = arr[last];
arr[last] = arr[max];
arr[max] = temp;
}
You goofed up the binary search intervals
public static int rBsearch(int[] L, int low, int high, int k) {
int mid = (low + high) / 2;
if (low > high) {
return -1;
} else if (L[mid] == k) {
return L[mid];
} else if (L[mid] < k) {
return rBsearch(L, mid + 1, high, k);
} else {
return rBsearch(L, low, mid - 1, k);
}
}
You did a mistake in calling the rBsearch method in the following lines
Instead of
else if (L[mid] < k) {
return rBsearch(L, k, mid + 1, high);
} else {
return rBsearch(L, k, low, mid - 1);
}
You should use
else if (L[mid] < k) {
return rBsearch(L, mid + 1, high,k); //the order of the parameters
} else {
return rBsearch(L, low, mid - 1,k);
}
Easiest way is:
Convert you array to list: Arrays.asList(array)
For sort: Collections#sort
For search: Collections#binarySearch
See this
Take Array From User
Sort Array using Build-in Function of Java...
then Search Element using Binary Search....
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int array[];
Scanner input = new Scanner(System.in);
System.out.println("Enter number of elements:");
int Size_Of_Array = input.nextInt();
array = new int[Size_Of_Array];
System.out.println("Enter " + Size_Of_Array + " integers");
for (int counter = 0; counter < Size_Of_Array; counter++)
array[counter] = input.nextInt();
Arrays.sort(array);
System.out.println("Sorting Array is :-");
for (int counter = 0; counter < Size_Of_Array; counter++)
System.out.println(array[counter]);
System.out.println("Enter the search value:");
int Searching_item = input.nextInt();
int First_Index=0;
int Last_Index=Size_Of_Array-1;
int Middle_Index=(First_Index+Last_Index)/2;
while(First_Index <= Last_Index)
{
if(array[Middle_Index] < Searching_item)
{
First_Index=Middle_Index+1;
}
else if ( array[Middle_Index] == Searching_item )
{
System.out.println(Searching_item + " found at location " + (Middle_Index + 1) + ".");
break;
}
else
{
Last_Index = Middle_Index - 1;
}
Middle_Index = (First_Index + Last_Index)/2;
if ( First_Index > Last_Index )
{
System.out.println(Searching_item + " is not found.\n");
}
}
}
}
Result of BinarySearch

Stuck in a simple quick sort implementation with random pivot

I'm reviewing algorithm stuff and stuck in a simple quick sort algorithm implementation in java
import java.util.Arrays;
import java.util.Random;
public class QuickSort {
int arr[];
boolean randomPick;
Random rand = null;
public QuickSort(int[] inputArray) {
arr = inputArray;
randomPick = false;
}
public QuickSort(int[] inputArray, boolean random) {
arr = inputArray;
if (random) {
randomPick = true;
rand = new Random(System.currentTimeMillis());
}
else {
randomPick = false;
}
}
public int[] sort() {
int start = 0;
int end = arr.length - 1;
try {
_sort(start, end);
}
catch (StackOverflowError e) {
System.out.println("StackOverflow: " + Arrays.toString(arr));
}
return arr;
}
private void _sort(int start, int end) {
int i = start;
int j = end;
int pivotLoc;
if (!randomPick) {
pivotLoc = (j + i) / 2;
}
else {
pivotLoc = rand.nextInt(j - i) + i;
}
int pivot = arr[pivotLoc];
while (i < j) { // swapping numbers around the pivot
while (arr[i] < pivot) {
i++;
}
while (arr[j] > pivot) {
j--;
}
if (i < j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
i++;
j--;
}
}
if (i - start > 1) {
_sort(start, i);
}
if (end - i > 1) {
_sort(i, end);
}
}
}
The code can either pick the middle number as the pivot or randomly pick a number as the pivot and it sorts the array by calling _sort recurrently. It works in the first case but fails in the second.
The situation is: when it reaches a subarray as this {3,5,5}, i==start==0 and j==end==2. Finally 5 and 5 are swapped, i becomes 2 and j becomes 1 (i++ and j--). Then since i - start>1 it will call _sort over and over and eventually evoke the stackoverflow error. However the error is supposed to happen in the first case (fixed pivot), which hasn't happened so far...
I don't know what's wrong with my code. I know it's not a pleasure to read code written by others but any help?
You've made a small mistake in your recursion condition, both the start and end compares are against i, the start should be against j
You have:
if (i - start > 1) {
_sort(start, i);
}
if (end - i > 1) {
_sort(i, end);
}
Needs to be:
if (j > start) {
_sort(start, j);
}
if (end > i) {
_sort(i, end);
}
And your i and j comparison needs to allow equals:
// here ----v
if (i <= j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
i++;
j--;
}

Categories