Need help in java search - java

Ok so I have to make a java program to search through an array using a binary search to find 45.3 but I am getting numerous class, interface, or enum expected errors starting after public static void main(String[] args) on line 23 can you guys help. thanks.
public class BinSearch
{
public static final int NOT_FOUND = -1;
public static int binarySearch(double[] arr, double x)
{
int low = 0;
int high = arr.length - 1;
int mid;
while (low <= high)
{
mid = (low + high) / 2;
if (arr[mid] > x)
{
high = mid - 1;
}
else if (arr[mid] < x)
{
low = mid + 1;
}
else
{
return mid+1;
}
}
return NOT_FOUND;
}
public static void main(String[] args)
{
int j,x;
double y,temp;
double[] arg= {-3.0, 10.0, 5.0, 24.0, 45.3, 10.5};
int i=0;
for (j = 1; j<arg.length;j++)
{
if(arg[i]>arg[j])
{
temp = arg[i];
arg[i] = arg[j];
arg[j] = temp;
}
i++;
System.out.print(arg[j-1]+",");
}
x = binarySearch(arg, 45.3);
System.out.print("45.3 found at ");
System.out.print(x);
}
}

It looks like you tried to use public class BinSearch as your main class. However, your parentheses enclose code before your main args.
public class MyClass {
//}// no bracket here
public static void main(String[] args) {
}
}
If you want to use a class to create Objects that use methods such as your public static final int , create a new class before.
class NewClass {
}
public class MyClass {
public static void main(String[] args) {
}
}

Related

Why is this Java code with Join/Fork framework to calculate Fibonacci numbers so slow?

What is wrong about this code ?
I am using Fork/Join Framework to make use of parallel Threads.
But to calculate Fibonacci takes much longer than normal calculation with just 1 thread.
public class FibonacciRecursiveTask extends RecursiveTask<Integer> {
public static final int THRESHOLD = 1;
int n ;
public FibonacciRecursiveTask(int n)
{
this.n = n;
}
#Override
protected Integer compute() {
if(n<= THRESHOLD)
{
//System.out.println(n);
return n;
}
FibonacciRecursiveTask left = new FibonacciRecursiveTask(n-1);
left.fork();
FibonacciRecursiveTask right = new FibonacciRecursiveTask(n-2);
Integer res1 = right.compute();
Integer res2 = left.join();
return res1 + res2;
}
}
class RecursiveTaskDemo
{
public static void main(String[] args)
{
FibonacciRecursiveTask task = new FibonacciRecursiveTask(44);
ForkJoinPool pool = new ForkJoinPool(8);
Integer res = pool.invoke(task);
System.out.println(res);
}
}
This is normal sequential with just 1 thread. This is like 4 times faster.
class Fib
{
public static void main(String[] args)
{
System.out.println(fib(44));
}
public static int fib(int n)
{
if(n <= 1)
{
return n;
}
return fib(n-2) + fib(n-1);
}
}

Connecting a variable in the main method with another method Java

The method should return true if the argument is even, or
false otherwise. The program’s main method should use a loop to generate 100 random integers. It should use the isEven method to determine whether each random number is even, or odd. All this is done!!!
This is the part where I can't figure it out!
When the loop is finished, the program should display the number of even numbers that were generated, and the number of odd numbers.
This is my code:
import java.util.Random;
public class EvenOdd
{
public static void main(String[] args)
{
Random random = new Random();
int randomInteger = 0;
for(int i = 0; i < 100; i++){
randomInteger = random.nextInt();
System.out.println("Random Integer: " + randomInteger);
EvenOdd(randomInteger);
}
}
public static void EvenOdd(int x)
{
int oddNumbers = 0;
int evenNumbers = 0;
if ((x % 2) == 0)
{
System.out.println("Even");
evenNumbers++;
}
else
{
System.out.println("Odd");
oddNumbers++;
}
}
}
Try with this:
public static void main(String[] args)
{
Random random = new Random();
int randomInteger = 0;
int oddNumbers = 0;
int evenNumbers = 0;
for(int i = 0; i < 100; i++){
randomInteger = random.nextInt();
System.out.println("Random Integer: " + randomInteger);
if(evenOdd(randomInteger)) evenNumbers++;
else oddNumbers++;
}
System.out.printf("Even numbers: %d - Odd numbers: %d", evenNumbers, oddNumbers);
}
public static boolean evenOdd(int x)
{
if ((x % 2) == 0)
{
System.out.println("Even");
return true;
}
else
{
System.out.println("Odd");
return false;
}
}
Your original approach doesn't work because you initialize to 0 the oddNumbers and evenNumbers variables everytime you call the method.
Define oddNumbers, evenNumbers variables as static class variables and after the loop you can print these 2 value.
Java is not JavaScript. Also, it does not have the ability of C++ as "Static variables in functions".
Variables declared inside a method are local. Variables initialization occurs every time your code reaches a variable definition inside the method and destroyed after exiting from the method.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
So you have such variants:
1) Count numbers inside your main method and return indicator from the utility method.
1.1) boolean
public static boolean isEven(int x){
return (x % 2) == 0;
};
1.2) enum
private enum NumberType {
EVEN,
ODD
}
public static NumberType getNumberType (int x) {
if ((x % 2) == 0) {
return NumberType.EVEN;
} else {
return NumberType.ODD;
}
};
2) Make your variables static:
public class EvenOdd {
private static int evenNumbersCount = 0;
private static int oddNumbersCount = 0;
public static void main(String[] args) {
// your code
}
public static void countNumberType (int x) {
if ((x % 2) == 0) {
++evenNumbersCount;
} else {
++oddNumbersCount;
}
}
}
3) In some sophisticated situations you will need to pass container to your method:
public class EvenOdd {
private static final String EVEN = "even";
private static final String ODD = "odd";
public static void main(String[] args) {
// initialize container
Map<String, Integer> evenOddCounts = new HashMap<>(2, 1);
evenOddCounts.put(EVEN, 0);
evenOddCounts.put(ODD, 0);
Random random = new Random();
int randomInteger = 0;
for (int i = 0; i < 100; i++) {
randomInteger = random.nextInt();
countNumberType(evenOddCounts, randomInteger);
}
System.out.println(evenOddCounts.toString());
}
public static void countNumberType(Map<String, Integer> counts, int x) {
if ((x % 2) == 0) {
counts.compute(EVEN, (numberType, count) -> ++count);
} else {
counts.compute(ODD, (numberType, count) -> ++count);
}
}
}

Heap Sort. What's wrong in this code?

I am able to create a Max Heap using a function heapify() but when i try to call it again(to delete max and create a sorted array) the program gets stuck/doesn't stop taking input. What's wrong?
Is this a memory problem?If I increase the number of calls by increasing the frequency of for loop it still works fine.
public class HeapSort
{
int[] heap;
public void sort(int length)
{
int temp;
for(int i=length;i>=1;i--)
{
heapify(i,length);
}
//if I try to call heapify again(even once) after this,the program gets stuck
}
public void heapify(int i,int l)
{
int lchild=2*i,rchild,max;
int temp;
while(lchild<=l)
{
rchild=(2*i)+1;
if(rchild<=l)
max=(heap[lchild]>heap[rchild])? lchild:rchild;
else
max=lchild;
if(heap[i]<heap[max])
{
temp=heap[i];
heap[i]=heap[max];
heap[max]=temp;
i=max;
}
lchild=2*i;
}
}
public static void main(String args[]) throws IOException
{
BufferedReader r= new BufferedReader(new InputStreamReader(System.in));
int length=Integer.parseInt(r.readLine());
HeapSort Heap=new HeapSort();
Heap.heap=new int[length+1];
for(int i=1;i<=length;i++)
Heap.heap[i]=Integer.parseInt(r.readLine());
Heap.sort(length);
for(int i=1;i<=length;i++)
System.out.print(Heap.heap[i]+" ");
}
}
Heapify should be done for length/2 iterations because it is like a tree structure.
Here is a complete code for heap sort...This sort array 's'
public class HeapSort {
public static void main(String[] args) {
String s[]={"aaaa","dddd","cccc","gggg","bbbbb"};
AsHeap(s);
HeapSort(s);
for(String x:s){
System.out.println(x);
}
}
public static void AsHeap(String s[]){
for( int i = s.length / 2; i >= 0; i-- ){
DownHeap( s, i, s.length );
}
}
public static void HeapSort(String[] s){
for(int i=s.length-1;i>0;i--){
swap(s,0,i);
DownHeap(s,0,i);
}
}
public static int getLeftChildIndex(int i){
return 2 * i + 1;
}
private static void DownHeap(String[] s, int i, int length) {
int indexOfChild;
String temp;
for(temp=s[i];getLeftChildIndex(i)<length;i=indexOfChild){
indexOfChild=getLeftChildIndex(i);
if(indexOfChild !=length-1 && s[indexOfChild].compareTo(s[indexOfChild+1])<0){
indexOfChild++;
}
if(temp.compareTo(s[indexOfChild])<0){
s[i] = s[indexOfChild];
} else{
break;
}
}
s[i] = temp;
}
public static void swap(String s[],int x,int y){
String temp=s[x];
s[x]=s[y];
s[y]=temp;
}
}
The while loop isn't terminating when there is no swap between the parent and the child(i.e. the parent is greater than the child).
The value of i(just above main method) doesn't change when parent is greater. Simply taking the line i=max outside the if block [if(heap[i]
Also,is there any sequence to learn Algorithms?If so,kindly guide me.
Thank you.

Aid with quick sort algorithm in java (netbeans)

I am quite new to programming and I am just starting using java. My task was to write a program using quick sort, I managed to write it but it always gives me an index out of bounds. Could anyone take a look at my code and help me by identifying what I am doing wrong? Thanks
This is the code for the main class.
package quicksort;
public class Quicksort {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int[] x = {5,3,10,1,9,8,7,4,2,6,0};
quicksort_class q = new quicksort_class(x);
q.sort();
for(int i = 0; i < 11-1; i++)
{
System.out.println(x[i]);
}
}
}
This is the code for quicksort_class.
public class quicksort_class {
int[] array1 = new int[11];
public quicksort_class(int[] w)
{
array1 = w;
}
public void partitionstep(int leftlimit, int rightlimit)
{
int LPointer = leftlimit;
int RPointer = rightlimit;
Random random = new Random();
int midpoint = random.nextInt(11);
int checknumber = array1[midpoint];
while(LPointer < RPointer)
{
while(array1[LPointer] <= checknumber)
{
LPointer = LPointer + 1;
}
while(array1[RPointer] >= checknumber)
{
RPointer = RPointer --;
}
swap(LPointer, RPointer);
partitionstep(leftlimit, midpoint - 1);
partitionstep(midpoint + 1, rightlimit);
}
}
public void swap(int x, int y)
{
int temp = array1[x];
array1[x] = array1[y];
array1[y] = temp;
}
public void sort()
{
partitionstep(0, array1.length - 1);
}
}
Your midpoint value should be calculated based on your leftLimit and rightLimit. It should not be a random value based off of the fixed value 11.

Java For Loop into Recursive function

public class For {
public static void main(String[] args){
for(int i=2; i<=1024; i *= 2){
System.out.println("Count is: " + i);
}
}
public class While {
public static void main(String[] args){
int i = 1;
while (i < 1024) {
i *= 2;
System.out.println("Count is: " + i);
}
}
public class DoWhile {
public static void main(String[] args){
int i = 1;
if (i < 1024) {
do { i*=2;
System.out.println("Count is: " + i);
} while (i < 1024);
}
}
How would one convert the for loop/while loop so it does the same thing, but using a recursive function?
Like so:
public class Recursive {
public void r(int i) {
if (i < 1024) {
i *= 2;
System.out.println("Count is: " + i);
r(i);
}
}
public static void main(String[] args) {
Recursive r = new Recursive();
r.r(1);
}
}
Take the loop of main and put it in its own function with an argument int i. In that function, rewrite the loop to
If the loop condition is false (i >= 1024), then return
Else, recursive call with argument i*2.
Call the function with argument 1 or 2, depending on which of your programs you're rewriting (they don't entirely match).
Recurrent loop can look like this:
class Main
{
public static void main(String[] args){
RecWhile(1);
}
public static void RecWhile(int i) {
if (i < 1024) {
i = i*2;
System.out.println("Count is: " + i);
RecWhile(i);
}
}
}
public class Test1 {
public static void main(String[] args) {
Test1 mainFunc = new Test1();
int[] arr = {1,2,4,3,5,6};
int start=0;
int end=arr.length;
mainFunc.callRecursiveFun(start, end, arr);
}
public int callRecursiveFun(int start, int end, int[] arr) {
int arrLen = end;
if(arrLen == 0) {
return 0;
} else {
System.out.println("Loop Index at "+start +": "+arr[start]);
}
return callRecursiveFun(start+1, end-1, arr);
}
}

Categories

Resources