I was wondering how to work with negative values and a negative target, right now my program gives index out of bounds errors whenever negative values are given to these variables. I need my hasSum function work with negative values for this project, I can't just assume positive.
import java.util.Stack;
import java.util.Scanner;
public class subsetSum {
static Scanner input = new Scanner(System.in);
static {
System.out.print("Enter the target (T)" + "\n");
}
/** Set a value for target sum */
static int TARGET_SUM = input.nextInt(); //this is the target
/** Store the sum of current elements stored in stack */
static int sumInStack = 0;
Stack<Integer> stack = new Stack<Integer>();
public static void main(String[] args) {
//the size is S
System.out.println("\n" + "Enter the size of the set (S)");
int values = input.nextInt(); //size = "values"
//value of each size entry
System.out.println("\n" + "Enter the value of each entry for S");
int [] numbers = new int[values];
for(int i = 0; i < values; i++) //for reading array
{
numbers[i] = input.nextInt();
}
if(hasSum(numbers, TARGET_SUM)){
System.out.println("\n" + "Can: ");
subsetSum get = new subsetSum(); // encapsulation
get.populateSubset(numbers, 0, numbers.length);
}else{
System.out.println("\n" + "Cannot");
}
}
//method based on dynamic programming O(sum*length)
public static boolean hasSum(int [] array, int sum)
{
int i;
int len = array.length;
boolean[][] table = new boolean[sum + 1][len + 1]; //this has to be changed for negative
//If sum is zero; empty subset always has a sum 0; hence true
for(i = 0; i <= len; i++){
table[0][i] = true;
}
//If set is empty; no way to find the subset with non zero sum; hence false
for(i = 1; i <= sum; i++){
table[i][0] = false;
}
//calculate the table entries in terms of previous values
for(i = 1; i <= sum; i++)
{
for(int j = 1; j <= len; j++)
{
table[i][j] = table[i][j - 1];
if(!table[i][j] && i >= array[j - 1]){
table[i][j] = table[i - array[j - 1]][j - 1];
}
}
}
return table[sum][len]; //this has to be changed for negative
}
public void populateSubset(int[] data, int fromIndex, int endIndex) {
/*
* Check if sum of elements stored in Stack is equal to the expected
* target sum.
*
* If so, call print method to print the candidate satisfied result.
*/
if (sumInStack >= TARGET_SUM) {
if (sumInStack == TARGET_SUM) {
print(stack);
}
// there is no need to continue when we have an answer
// because nothing we add from here on in will make it
// add to anything less than what we have...
return;
}
for (int currentIndex = fromIndex; currentIndex < endIndex; currentIndex++) {
if (sumInStack + data[currentIndex] <= TARGET_SUM) {
stack.push(data[currentIndex]);
sumInStack += data[currentIndex];
/*
* Make the currentIndex +1, and then use recursion to proceed
* further.
*/
populateSubset(data, currentIndex + 1, endIndex);
sumInStack -= (Integer) stack.pop();
}
}
}
/**
* Print satisfied result. i.e. 5 = 1, 4
*/
private void print(Stack<Integer> stack) {
StringBuilder sb = new StringBuilder();
for (Integer i : stack) {
sb.append(i).append(",");
}
// .deleteCharAt(sb.length() - 1)
System.out.println(sb.deleteCharAt(sb.length() - 1).toString());
}
}
Are you trying to find a sum of subset or a subarray?
If a subset, then a simple recursion could do the trick, e.g.:
public static boolean hasSum(int [] array, int sum)
{
return hasSum(array, 0, 0, sum);
}
private static boolean hasSum(int[] array, int index, int currentSum, int targetSum) {
if (currentSum == targetSum)
return true;
if (index == array.length)
return false;
return hasSum(array, index + 1, currentSum + array[index], targetSum) || // this recursion branch includes current element
hasSum(array, index + 1, currentSum, targetSum); // this doesn't
}
If you're trying to find a subarray, I'd use prefix sums, e.g.:
public static boolean hasSum(int [] array, int sum)
{
int[] prefixSums = new int[array.length];
for (int i = 0; i < prefixSums.length; i++) {
prefixSums[i] = (i == 0) ? array[i] : array[i] + prefixSums[i - 1];
}
for (int to = 0; to < prefixSums.length; to++) {
if (prefixSums[to] == sum)
return true; // interval [0 .. to]
for (int from = 0; from < to; from++) {
if (prefixSums[to] - prefixSums[from] == sum)
return true; // interval (from .. to]
}
}
return false;
}
BTW I think reading the input values from Scanner inside the static initializer is a bad idea, why don't you move them to main()?
Related
Algorithm:
Procedure SELECT( k,S)
{ if ISI =1 then return the single element in S
else { choose an element a randomly from S;
let S1,S2,and S3 be he sequences of elements in S
less than, equal to, and greater than m, respectively;
if IS1I >=k then return SELECT(k,S1)
else
if (IS1I + IS2I >=k then return m
else return SELECT(k-IS1I-IS2I , S3);
}
}
The question is to implement the first algorithm for finding the kth smallest integer in a set of integers and test your program for different sets of integers generated by a random number generator.
Below is my solution.
import java.util.Random;
import java.util.Scanner;
public class main {
private static Random rand = new Random();
private static Scanner keyboard = new Scanner(System.in);
public static int firstAlgorithm(int k, int[] S) {
int m = S[rand.nextInt(S.length)];
int[] S1 = new int[S.length];
int[] S2 = new int[S.length];
int[] S3 = new int[S.length];
int p = 0;
int q = 0;
int r = 0;
if (S.length == 1)
return S[0];
for (int i = 0; i < S.length; i++) {
if (S[i] < m) {
S1[p] = S[i];
p++;
} else if (S[i] == m) {
S2[q] = S[i];
q++;
} else {
S3[r] = S[i];
r++;
}
}
S1 = trimToSize(S1, p);
S2 = trimToSize(S2, q);
S3 = trimToSize(S3, r);
if (S1.length >= k)
return firstAlgorithm(k, S1);
else if (S1.length + S2.length >= k)
return m;
else
return firstAlgorithm(k - S1.length - S2.length, S3);
}
private static int[] trimToSize(int[] arr, int size) {
int[] temp = new int[size];
for (int i = 0; i < size; i++) {
temp[i] = arr[i];
}
return temp;
}
public static void printArray(int[] S) {
for (int i = 0; i < S.length; i++) {
System.out.print(S[i] + "\t");
if (i % 10 == 9)
System.out.println();
}
}
// start main method
public static void main(String[] args) {
System.out.print("Enter the size of an array: ");
int size = keyboard.nextInt();
while (size < 1) {
System.out.println("Size of the array should be greater than 0.");
System.out.print("Enter the size of an array: ");
size = keyboard.nextInt();
}
System.out.print("Enter the value of k: ");
int k = keyboard.nextInt();
while (k < 1 || k > size) {
System.out.println("Value of k should be in the range 1-" + size + ".");
System.out.print("Enter the value of k: ");
k = keyboard.nextInt();
}
int[] S = new int[size];
for (int i = 0; i < size; i++) {
S[i] = 100 + rand.nextInt(900);
}
System.out.println("\nRandom values generated in the array:");
printArray(S);
System.out.println();
System.out.println(k + "th smallest value in the array using Algorithm #1: " + firstAlgorithm(k, S));
}
}
But I need to implement the above algorithm without using a temporary array for partitioning. How can I do it?
The algorithm is Dijkstra's 3-way partition.
You will have to modify the original S.
Untested (pseudo) code ahead
public static int partition(int left, int right, int[] S) {
int m = rand.nextInt(right-left); // protect against malicious data
swap(S[left+m], S[right]);
int equal = left;
while (left < right) {
if (a[left] < a[n])
swap(S, left++, equal++)
else if (a[left] == a[n])
swap(S, left, --right);
else
left++;
}
return left, equal;
}
public static int firstAlgorithm(int k, int left, int right, int[] S) {
if (left == right)
return S[left];
int p, e = partition(left, right, S); // returns 2 values. S1=[0,p), S2=[p,e), S3=[e, n)
if (p >= k)
return firstAlgorithm(k, left, p, S);
else if (e >= k) // p < k
return S[p]; // p is the first equal, e is first larger than equal
else // e < k
return firstAlgorithm(k, e, right, S);
}
// test
S = {1, 4, 2, 6, 2};
k = 2;
int result = firstAlgorithm(2, 0, S.length-1, S);
assert(result == 2);
Warning syntax and off-by-one errors guarantied.
See here multiple ways to return 2 values in java.
I am currently learning Java. Below is a list of methods from a simple Java program I have written. Is there anything that stands out in these methods would cause the execution of the program to go very slow? It's taking four seconds to execute using an array containing just 6 integers:
EDITED: here's the entire program as requested. I wrote it in Textpad. I realise it is not the most efficient algorithm. It does what it is supposed to do, but takes too long to do it.
import java.util.*;
public class Supermarket
{
public static void main(String [] args)
{
int[] custTimes =
{
1, 6, 7, 4, 4, 3, 5, 1, 2, 1, 3, 6, 4
};
int checkOuts = 6;
int answer;
answer = Solution.solveSuperMarketQueue(custTimes, checkOuts);
System.out.println("Answer is " + answer);
}
}//~public class Supermarket...
class Solution
{
static int myTotal;
static int solveSuperMarketQueue(int[] customers, int n)
{
// ******************* INITIALIATION ***********************
myTotal = 0;
int len = customers.length; // length of customer queue
if (len < 1)
{
return 0;
}
int[] till = new int[n]; // array to store all tills and till queues
int tillMin; // Minimum time
int tillMax; // Maximum time
// Put the customers into an arraylist:
ArrayList<Integer> times = new ArrayList<Integer>();
for (int i = 0; i < len; i = i + 1)
{
times.add(i, customers[i]);
}
// create the array of tills and set all queue intial values to 0
for (int i = 0; i < n; n = n + 1)
{
till[i] = 0;
}
// Move the queue to tills to start off
ReturnPair result = copyQueue(till, times);
till = result.getArr();
times = result.getList();
int s = times.size();
tillMax = getMaxTime(till);
tillMin = getMinTime(till);
// ***************** END OF INITIALIATION ******************
// *****************MAIN LOOP ******************************
while (tillMax > 0)
{
// Find customer(s) with least time use that time to move all queues
// and update myTotal time.
// STEP 1: get minimum time in tills array (ignore zero)
tillMin = getMinTime(till);
// STEP 2: subtract minimum value from all the tills, but not if till has a zero
if (tillMin > 0)
{
till = subtractTime(till, tillMin);
}
// Move the queue to tills
if (s > 0)
{
result = copyQueue(till, times);
till = result.getArr();
times = result.getList();
}
tillMax = getMaxTime(till);
tillMin = getMinTime(till);
}
return myTotal;
// **************** END OF LOOP *****************************
}//~public static int solveS...
// ****************** METHODS **********************************
// Method to move queue foward
// For each till, a time is copied from the customer array.
// The values are copied in order.
// The value is coped only if array value is zero.
private static ReturnPair copyQueue(int[] arr, ArrayList<Integer> arrList)
{
int n = arr.length; // for each till...
for (int i = 0; i < n; i = i + 1)
{
if (arr[i] == 0 && arrList.size() > 0) // only copy if it current till value is 0 AND arrayList value exists
{
arr[i] = arrList.get(0);
arrList.remove(0);
}
}
// returns an instance of the object myResult which is a container for an array and an arraylist
return new ReturnPair(arr, arrList);
}
// Method to get minimum time from array (but not zero).
private static int getMinTime(int[] arr)
{
int minValue = 0;
// make sure arr[i] isn't zero.
for (int i = 0; i < arr.length; i = i + 1)
{
if (arr[i] != 0)
{
minValue = arr[i];
break;
}
}
// Find minimum value that isn't zero.
for (int i = 1; i < arr.length; i = i + 1)
{
if (arr[i] != 0 && arr[i] < minValue)
{
minValue = arr[i];
}
}
return minValue;
}//~static int getMinTime(in...
// Method to subtract minimum time from tills
private static int[] subtractTime(int[] arr, int min)
{
int n = arr.length;
for (int i = 0; i < n; i = i + 1)
{
if (arr[i] != 0)
{
arr[i] = arr[i] - min;
}
}
// update myTotal
myTotal = myTotal + min;
return arr;
}//~static void subtractTime...
private static int getMaxTime(int[] arr)
{
int maxValue = arr[0];
for (int i = 1; i < arr.length; i = i + 1)
{
if (arr[i] > maxValue)
{
maxValue = arr[i];
}
}
return maxValue;
}
}//~class Solution...
// Special class designed to return an array and an array list as an object
class ReturnPair
{
// set up fields
int[] newArr;
ArrayList<Integer> newArrList;
// define method
public ReturnPair(int[] first, ArrayList<Integer> second)
{
this.newArr = first;
this.newArrList = second;
}
public int[] getArr()
{
return newArr;
}
public ArrayList<Integer> getList()
{
return newArrList;
}
}
for (int i = 0; i < n; n = n + 1)
This line is incrementing n instead of i. it will loop until n overflows. It should be:
for (int i = 0; i < n; i++)
Because int arrays are initialized to 0 anyway, you can remove this loop completely.
public class LoopTest {
public static void main(String[] args) {
int[] myarr = {12, 12, 12, 8, 15, 15};
//Boolean array to mark the elements,defaults false
boolean[] b = new boolean[myarr.length];
//Compare Consecutive values and mark them true if equal
for (int i = 1; i < myarr.length; i++) {
if (myarr[i - 1] == myarr[i]) {
b[i - 1] = b[i] = true;
}
}
int sum = 0;
//Add all the values in myarr with indices marked as equal
for (int i = 0; i < b.length; i++) {
if (b[i]) {
sum += myarr[i];
}
}
System.out.println(sum);
}
}
Output:
66
Explanation:
12+12+12+15+15
Is there a better/cleaner way to compare values in array and add only values if they are equal, without using utility methods?
You could keep a running count of duplicate items and add them to your sum when the run ends.
int[] myarr = {12, 12, 12, 8, 15, 15};
// assumes > 0 length
int count = 1;
int sum = 0;
for (int i = 1; i < myarr.length; i++) {
if (myarr[i] == myarr[i - 1]) {
count++;
} else {
if (count > 1) {
sum += count * myarr[i - 1];
}
count = 1;
}
}
// handle if last elements are duplicates
if (count > 1) {
sum += count * myarr[myarr.length - 1];
}
System.out.println(sum);
You can solve this with linear efficiency. This program is a little bit cleaner and works in all conditions, checking all the edge cases. It results in the correct answer of 66 for your problem. It loops through the array, and checks if each element is consecutive (same as previous element). If so, it adds the element's value onto the sum. Edge cases need to be included to account for the starting elements of each consecutive block, which have to be added to the sum as well.
private static int consecutiveCompare(int[] array)
{
int sum = 0;
for (int i = 1; i < array.length; i++)
{
if (array[i] == array[i-1])
{
if (i == 1)
{
sum += array[i];
}
else if (array[i] != array[i-2])
{
sum += array[i];
}
sum += array[i];
}
}
return sum;
}
The following code will work:
public class LoopTest {
public static void main(String[] args) {
int[] myarr = {12, 12, 12, 8, 15, 15};
int sum = 0;
int occ = 1;
for (int i = 1; i < myarr.length; i++) {
if (myarr[i - 1] == myarr[i]) {
occ++;
} else {
if (occ > 1) {
sum += (occ * myarr[i - 1]);
}
occ = 1;
}
if (i == myarr.length - 1) {
if (occ > 1) {
sum += (occ * myarr[i - 1]);
}
}
}
System.out.println(sum);
}
}
Haven't tested all edge cases, here is what I have in my mind:
public class LoopTest {
public static void main(String[] args) {
int[] myarr = {1,1,1,2,2,3,3,4};
//Boolean array to mark the elements,defaults false
boolean[] b = new boolean[myarr.length];
//Last value tracker.
int lastVal = myarr[0];
//Count occurrences in a sequence.
int cntr = 1;
//Sum counter.
int sum = 0;
//Compare Consecutive values and mark them true if equal
for (int i = 1; i < myarr.length; i++) {
if (myarr[i] == lastVal) {
cntr++;
//If last sequence mathching.
if (i == myarr.length-1) {
sum += lastVal * cntr;
}
} else {
if (cntr > 1) {
sum += lastVal * cntr;
//Reset counter.
cntr = 1;
}
lastVal = myarr[i];
}
}
System.out.println(sum);
}
}
I have written a method to evaluate a Pascal's triangle of n rows. However when I test the method I receive the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
Here is the code:
public static int[] PascalTriangle(int n) {
int[] pt = new int[n + 1];
if (n == 0) {
pt[0] = 1;
return pt;
}
int[] ppt = PascalTriangle(n - 1);
pt[0] = pt[n] = 1;
for (int i = 0; i < ppt.length; i++) {
pt[i] = ppt[i - 1] + ppt[i];
}
return pt;
}
Please let me know if you have any ideas for how the code could be edited to fix the problem.
for(int i = 0; i < ppt.length; i++)
{
pt[i] = ppt[i-1] + ppt[i];
In your first iteration, i == 0 and so (i-1) == -1. This is the cause of the error.
You can special handle the boundaries to avoid this. Or as the others have suggested, start i at 1 instead of 0.
Here is some code a friend of mine came up with
import java.util.Scanner;
public class Pascal {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows to print: ");
int rows = scanner.nextInt();
System.out.println("Pascal Triangle:");
print(rows);
scanner.close();
}
public static void print(int n) {
for (int i = 0; i < n; i++) {
for (int k = 0; k < n - i; k++) {
System.out.print(" "); // print space for triangle like structure
}
for (int j = 0; j <= i; j++) {
System.out.print(pascal(i, j) + " ");
}
System.out.println();
}
}
public static int pascal(int i, int j) {
if (j == 0 || j == i) {
return 1;
} else {
return pascal(i - 1, j - 1) + pascal(i - 1, j);
}
}
}
In this code:
pt[0] = pt[n] = 1;
for(int i = 0; i < ppt.length; i++)
{
pt[i] = ppt[i-1] + ppt[i];
}
the problem is that when i is 0, you're trying to access ppt[i-1] which is ppt[-1]. The thing to notice is that when i is 0, you don't need to execute the statement that sets pt[i], because you already set pt[0] up before the loop! Try initializing i to 1 instead of 0.
Improvement in #Clemson code using Dynamic Programming :
class Solution {
int[][] dp ;
public List<List<Integer>> generate(int numRows) {
dp = new int[numRows][numRows];
List<List<Integer>> results = new ArrayList<>();
pascal(results, numRows);
return results;
}
private void pascal(List<List<Integer>> results, int numRows) {
for(int i = 0; i < numRows; i++) {
List<Integer> list = new ArrayList<>();
for(int j = 0; j <= i ; j++) {
list.add(dfs(i, j));
}
results.add(list);
}
}
private int dfs(int i, int j) {
if(j == 0 || i == j) return 1;
if(dp[i][j] != 0) return dp[i][j];
return dp[i][j] = dfs(i - 1, j - 1) + dfs(i - 1, j );
}
}
This isn't the solution to your code but it is solution to printing Pascals Triangle using only recursion which means no loops, using the combinations formula. All it needs is a main method or demo class to create an instance of the PascalsTriangle class. Hope this helps future Java students.
public class PascalsTriangle {
private StringBuilder str; // StringBuilder to display triangle
/**
* Starts the process of printing the Pascals Triangle
* #param rows Number of rows to print
*/
public PascalsTriangle(int rows) {
str = new StringBuilder();
printTriangle(rows, str);
}
/**
* Uses recursion to function as an "outer loop" and calls
* itself once for each row in triangle. Then displays the result
* #param row The number of the row to generate
* #param str StringBuilder to insert each row into
*/
public static void printTriangle(int row, StringBuilder str) {
// calls itself until row equals -1
if (row >= 0) {
// calls lower function to generate row and inserts the result into front of StringBuilder
str.insert(0, getRow(row, 0) + "\n");
// calls itself with a decremented row number
printTriangle(row - 1, str);
} else {
// when the base case is reached - display the result
JOptionPane.showMessageDialog(null, str);
System.exit(0);
}
}
/**
* Uses recursion to act as the "inner loop" and calculate each number in the given row
* #param rowNumber Number of the row being generated
* #param elementNumber Number of the element within the row (always starts with 0)
* #return String containing full row of numbers or empty string when base case is reached
*/
public static String getRow(int rowNumber, int elementNumber) {
// calls itself until elementNumber is greater than rowNumber
if (elementNumber <= rowNumber) {
// calculates element using combinations formula: n!/r!(n-r)!
int element = fact(rowNumber) / (fact(elementNumber) * (fact(rowNumber - elementNumber)));
// calls itself for each element in row and returns full String
return element + " " + getRow(rowNumber, elementNumber + 1);
} else return "";
}
/**
* Helper function that uses recursion to calculate factorial of given integer
* #param n Number to calculate factorial
* #return Factorial
*/
public static int fact(int n) {
if (n <= 0)
return 1;
else
return n * fact(n - 1);
}
I have instantiated a 2D array of an editable number of rows and a set number of three columns.
It is randomly filled with 0's and 1's using the Random .nextInt(2) method.
After the array is filled, I want to be able to search the array and return the first occurrence of a 0.
How can I do this?
For example, if i had an array that looked something like this:
1 1 0
0 1 0
1 1 1
The first occurence would be at (0,3). I want to search the array horizontally and when it reaches the third column (the end), it will go to the next row.
Note: I originally tested the following section of code with a 2D array that was completely filled with 0's and when I manually inserted 1's in the array and then tried to search for the first occurence of a 0 it worked. However, the code doesn't work when the array is randomly filled..
public String findNextAvailable()
{
for (int i=0; i<seatlist.length; i++)
{
for (int j=0; j<seatlist[i].length; j++)
{
int k=0;
if (seatlist[0][0]==0)
{
nextavailable= seatchart[0][0];
break;
}
else
if(seatlist[k][j]==0)
{
nextavailable= seatchart[k][j];
break;
}
else
{ k++;
if(seatlist[k][j]==0)
{
nextavailable= seatchart[k][j];
break;
}
}
}
}
return nextavailable;
}
Thanks in advance!
for (int i = 0; i < seats.length; i++) {
for (int j = 0; j < seats[i].length; j++) {
if (seats[i][j] == 0) {
return "Next available seat at position: [" + i + "][" + j + "]";
}
}
}
return "No seat available";
Although you might want to create a seat object instead that is easier to work with:
public class Seat {
private int row;
private int column;
public Seat(int row, int column){
this.row = row;
this.column = column;
}
public int getRow() {
return row;
}
public int getColumn() {
return column;
}
}
and replace the returning of a string with:
return new Seat(i,j);
well when you break in the inner loop, you still execute again the outer loop and you wind up replacing what you think is your final result by the next run of the outer loop. rather than use break, just return right there.
You need to return the positions of the first encountered 0, so why are you breaking out of the if statement, the outer loop will still run!
Simply create an integer array:
int[] pos=new array[2];
Change the return type:
public int[] findNextAvailable(){
In each of the if statements change the contents so that it reads:
pos[0]=i;
pos[1]=j;
return pos;
The end result will look something like this:
public int[] findNextAvailable()
{
int[] pos=new array[2];
for (int i=0; i<seatlist.length; i++)
{
for (int j=0; j<seatlist[i].length; j++)
{
if (seatlist[i][j]==0)
{
pos[0]=i;
pos[1]=j;
return pos;
}
}
}
//none found so return minus one.
pos[0]=-1;
pos[1]=-1;
return pos;
}
there are many different types of searches, some faster and some easier to do. Here's a program i made that has methods for all types of them. you will have to modify them a bit so it will search a 2d array but it shouldn't be too hard.
'
package linear_search;
import java.util.Arrays;
import java.util.Scanner;
public class Linear_search {
int[] array = {10,12,42,7,22,1,3,4,5,9};
int ans;
int num;
int min;
int max;
void start(){
arraySort(array);
dump(array);
Scanner scan = new Scanner(System.in);
System.out.println("Enter a value to search:");
num = scan.nextInt();
ans = recursiveBinarySearch(array, 0, array.length-1);
if(ans == -1){
System.out.println("Your value was not found");
} else {
System.out.println("Your value was found at position " + ans);
}
}
void dump(int[] array){
for(int i = 0; i < array.length ; i++){
System.out.print(array[i] + " ");
}
System.out.println();
}
int linearsearch(int[] array){
for(int i = 0; i < array.length; i++){
if(array[i] == num){
return i;
}
}
return -1;
}
int binarysearch(int[] array){
min = 0;
max = array.length -1;
int mid = (min + max) / 2;
while(array[mid] != num){
if(num > array[mid]){
min = mid+1;
mid = (min + max) / 2;
}
if(num < array[mid]){
max = mid-1;
mid = (min + mid) / 2;
}
if(min == max && array[mid] != num){
return -1;
}
}
return mid;
}
int recursiveBinarySearch(int[] array, int min, int max){
int mid = (min + max) / 2;
if(array[mid] == num){
return mid;
}
if(min == max && array[mid] != num){
return -1;
}
if(num > array[mid]){
return recursiveBinarySearch(array, mid+1, max);
}
if(num < array[mid]){
return recursiveBinarySearch(array, min, mid-1);
}
return mid;
}
void arraySort(int[] a){
Arrays.sort(array);
}
public static void main(String[] args) {
Linear_search main = new Linear_search();
main.start();
}
}
'
you will just have to remove the scanner and hard code in "0" for the default value you should search for.