Question: Help needed in implementing a java random quicksort algorithm that returns the index of the pivot value once it is partitioned the first time For

Help needed in implementing a java random quicksort algorithm that returns the index of the pivot value once it is partitioned the first time

For example, if the array is [5, 2, 9, 12, 6, 8, 3, 7] and the random value for the pivot is 6 (index 4) the algorithm could return this resulting array [ 5, 2, 3, 6, 7, 8, 9, 12 ]. The algorithm returns the value 3 (the index of the pivot after the partition algorithm has been executed), indicating that the left subarray is [ 5, 2, 3 ] and the right subarray is [ 7, 8, 9, 12 ]. My code is returning the index value of the pivot after its partition, but my array did not sort the integers properly, [5.0, 2.0, 9.0, 12.0, 7.0, 3.0, 8.0, 6.0] (the 12 is in the index value 3, but there are numbers less than 12 still on the right side)

Any assistance would be appriciated. I Will like and comment.

** code is below **

import java.util.Random; import java.util.Arrays; public class randomQuickSort { public static void swap(double[] arr, int p, int t) { double temp = arr[p]; arr[p] = arr[t]; arr[t] = temp; } public int partition(double[] arr, int left, int right) { // create a random pivot int pivot = (new Random()).nextInt(right); // Base case -- or reverse of the base case if (left < right) { int bot = pivot + 1; // Avoids re-sorting the pivot int top = right; while (bot <= top) { // Count up from left, down from right, swap ... on the next slide while (bot <= right && arr[bot] <= arr[pivot]) { ++bot; } while (top >= bot && arr[top] > arr[pivot]) { --top; } if (bot <= right && bot < top) { swap(arr, bot, top); } } swap(arr, pivot, right); // pivot to the middle return top; } return left; } public int quicksort (double [] arr, int left, int right) { int p = 0; if (left < right) { // Base case (right < left) is NOP p = partition(arr, left, right); } return (int) arr[p]; } public static void main (String[]args) { randomQuickSort rq = new randomQuickSort(); // testing example array to see if it returns index value of pivot double [] arr3 = {5, 2, 9, 12, 6, 8, 3, 7}; int result = rq.quicksort(arr3, 0, arr3.length-1); System.out.println(result); System.out.println(Arrays.toString(arr3)); } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!