So, I've been given a problem to implement a program that returns true
if an array of sorted integers contains numbers greater than I
but less than u
, false
otherwise.
I've identified that a quick sort algorithm would be a good way to sort the array, because I can't know how the user will enter it in - then, I feed the sorted array to binary search and find out if the array contains integers within the specified range. The problem is, I can't seem to be able to reason about this, since it is not one value I want to find here, but a range. Also, I want to implement this recursively if possible.
Here's what I have so far:
import java.util.Scanner;
class RangeBinarySearch {
public static int[] quickSort(int[] unsortedArray, int left, int right) {
int[] sortArray = unsortedArray;
if (left >= right)
return sortArray;
int pivot = unsortedArray[(left + right) / 2];
int i = left;
int j = right;
while (i <= j) {
while (unsortedArray[i] < pivot)
i++;
while (unsortedArray[j] > pivot)
j--;
if (i <= j) {
int temp = unsortedArray[i];
unsortedArray[i] = unsortedArray[j];
unsortedArray[j] = temp;
i++;
j--;
}
}
if (left < j)
quickSort(unsortedArray, left, j);
if (right > i)
quickSort(unsortedArray, i, right);
return sortArray;
}
public static boolean withinRangeSorted(int[] sortedArray, int I, int u) {// This uses binary search
int start = 0;
int end = sortedArray.length - 1;
int mid = sortedArray[(start + end) / 2];
if (sortedArray[start] > u || sortedArray[end] < I)
return false;
else if (sortedArray[start] > I && sortedArray[end] < u)
return true;
else {
// What to do here? I am stuck!
}
return false;
}
public static void main(String[] args) {
int size;
int inum;
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of the array: ");
size = input.nextInt();
int[] unsortArray = new int[size];
for (int i = 0; i < size; i++) {
int c = i + 1;
System.out.println("Enter element " + c + " to be added to the array: ");
inum = input.nextInt();
unsortArray[i] = inum;
}
int left = 0;
int right = size - 1;
int[] sortedArray = quickSort(unsortArray, left, right);
int I; // greater than
int u; // less than
System.out.println("Enter range starting point: ");
I = input.nextInt();
System.out.println("Enter range end point: ");
u = input.nextInt();
boolean result = withinRangeSorted(sortedArray, I, u);
System.out.println(result);
}
}
The problem is, I just can't seem to figure out how to structure the withinRangeSorted
method.
I am mainly confused about what sort of parameters should the method even take if I am searching for a value greater than I
and less than u
.
I feel like I'm on the right track here, but I can't seem to be able to formulate the recursion properly.
Any help would be much appreciated.