How to run instance methods from main - java

Sorry but I'm having a major brain fart here (guess that's what a few days of little sleep get you). Without changing anything to static how can I make a main() that will run this.
package merger;
import java.util.Random;
public class another {
public int[] numbers;
private final static int size = 100;
private static int maxNumber = 30;
private final static int limit = 10;
public int number;
private boolean Insertion = false;
public void arraytosort(){
numbers = new int[size];
Random number = new Random();
for (int i=0; i< numbers.length; i++){
numbers[i] = number.nextInt(maxNumber);
}
test(numbers);
}
public void test(int[] array){
this.numbers = array;
number = array.length;
mergesort(0,number - 1);
}
public void mergesort(int low, int high){
if(Insertion || high-low < limit){
insertionsort(low, high);
return;
}
if (low<high){
int middle = (low+high) / 2;
mergesort(low, middle);
mergesort(middle +1, high);
merge(low,middle,high);
return;
}
}
public void merge(int low, int middle, int high){
int[] temp = new int[number];
for (int i=low;i<=high; i++){
temp[i] = numbers[i];
}
int i = low;
int j = middle+1;
int k = low;
while (i<=middle || j<=high){
if (temp[i] <= temp[j]){
numbers[k] = temp[i];
i++;
}
else{
temp[k] = temp[j];
j++;
}
k++;
}
while (i<=middle){
temp[k] = temp[i];
k++;
i++;
}
temp = null;
return;
}
public void insertionsort(int low, int high){
for(int i=low+1;i<=high;i++){
int t = numbers[i];
for(int j = i-1; j>=low; j--){
if(t>numbers[j]) break;
numbers[j+1] = numbers[j];
numbers[j+1] = t;
}
}
}
/**
* #param args
*/
public static void main(String[] args){
}
}
I just need to be able to test it to see if this is working. In my head it seems like it should work.
Thanks

Without changing anything to static how can I make a main() that will run this.
You have to create an instance of the class:
public static void main(String[] args){
another instance = new another();
instance.whateverMethodYouLike();
}
BTW, please follow the Java convention and name classes with a capital first letter.

public static void main(String[] args)
{
another myObject = new another();
myObject.arraySort(); //will call test which will call mergesort
myObject.insertionSort(0,myObject.numbers.size()-1); //nothing calls insertion sort
}
PLEASE following code conventions like capitalizing first letter of class name and camelCasing for methods/variables.
If you want to see the sorted output, print the array on screen.
public variables is bad, bad, bad make them private (like numbers[]) in your case...
In the main method you "create" the instance of the object of that class and not directly call methods. It's a 'special' method so to speak different from other public/private/static methods...
I suggest reading up on some elementary java book like thinking in java which is available for free online...

Related

Quicksort - Java

I'm implementing Quicksort but the answer does not display correctly. I have been finding the errors but don't know where I get wrong. The answer is still 3,5,1,8,6,7,9,2. Can someone tell me what is wrong in my code?
public class quicksortJava {
public static void main (String args[]) {
int A [] = {3,5,1,8,6,7,9,2};
quicksort(A,0,A.length-1);
for(int i = 0; i < A.length; i++ ){
System.out.print(A[i]+" ");
}
}
public static void quicksort(int[]A,int start,int end){
if (start < end){
int pIndex = partition(A,start,end);
quicksort(A,start,pIndex-1);
quicksort(A,pIndex+1,end);
}
}
public static int partition(int[]A,int start,int end){
int pivot = A[end];
int pIndex = start;
for (int i = start;i < end; i++){
if (A[i] <= pivot){
swap(A[i],A[pIndex]);
pIndex++;
}
}
swap(A[pIndex],A[end]);
return pIndex;
}
public static void swap(int A,int B){
int temp = A;
A = B;
B = temp;
}
Your swap method does not work, because you are only changing the local variables "A" and "B" within the method "swap". You are not actually changing anything in the list.
Try this:
public static void swap(int a, int b) {
int tmp = list[a];
list[a] = list[b];
list[b] = tmp;
}
You'll need to change all the calls to "swap", too, so they pass an index rather than a value.
(Also, Java variables are lowercase / camelCase, not uppercase. You have multiple variables called "A", which makes everything confusing.)
Here is the correct answer
public static int partition(int[]A,int start,int end){
int pivot = A[end];
int pIndex = start;
for (int i = start;i < end; i++){
if (A[i] <= pivot){
//swap(i,pIndex);
int temp = A[i];
A[i] = A[pIndex];
A[pIndex] = temp;
pIndex++;
}
}
//swap(A[pIndex],A[end]);
int temp = A[pIndex];
A[pIndex] = A[end];
A[end] = temp;
return pIndex;
}

SOLVED How to write a method to sort numbers from an array from low to high

There's an error in this code:
ArraySortSearch.java:12: error: incompatible types: int cannot be
converted to int[]
int [] mySorted = sort(myNumbers);
^ ArraySortSearch.java:56: error: incompatible types: int[] cannot be converted to int
return a;
I just started learning Java not long ago. This is so difficult:( How do I solve this?
//not allowed to use import java.util
public class ArraySortSearch { // shouldn't be changed from here
public static void main(String[] args) {
int [] myNumbers = {15,12,23,0,10,55,2,78,9,6,1,4,11};
System.out.println("Looking for numer 55: ");
System.out.println(find(myNumbers,55));
System.out.println("Sorted Array:");
int [] mySorted = sort(myNumbers);
for(int i = 0; i< mySorted.length; i++) {
System.out.println(mySorted[i]);
}
} //to here
public static int find(int [] a, int number){ //this method works
for(int i=0; i<a.length; i++){
if(a[i]==number){
return i;
}
else{
continue;
}
}
return -1;
}
public static int sort(int [] a){ //this method is the problem
for(int b=0; b<a.length; b++){
for(int i =1; i<a.length; i++){
if(a[b]<a[i]){
int temp = a[b];
a[b] = a[i];
a[i] = temp;
}
}
}
return a;
}
}
Thank you in advance!
Your return type is an int but a is an array. Since you are sorting the array in place, just have a return type of void and no need to return anything.
Also, make your outer loop go to a.length-1 and have your inner loop start at b+1.

Why does my bubble sort method not work?

Sorry I am still learning programming. Java just stops and seems to be processing something. It says "Building java application Javaapplication2" then just sits there doing nothing. What have a I done to cause this ?
package javaapplication2;
public class JavaApplication2 {
public static void main(String[] args) {
int a [] = {1,2,3};
int c [] = Sortarray.sortlowhigh(a);
int i = 0;
while (i<c.length){
System.out.println("array is" + c[i]);
i++;
}
}
}
package javaapplication2;
public class Sortarray {
public static int[] sortlowhigh(int a[])
{
int i = 0;
int j = 0;
while(j<a.length){
while(i<a.length){
if (a[i]>a[i+1]){
/* store low value in temp*/
int temp = a[i+1];
/* assign low value to be the higher value*/
a[i+1] = a[i];
/* assign the old higher value to be the lower value stored in temp*/
a[i]=temp;
}
j++;
}
}
return a;
}
}
My code is above. A while ago I wrote a sort and remove duplicates method now I want to put them into a class but I am doing something wrong. Please help. Thanks.
I try your code and I can see that you have a infinite loop in the class Sortarray. The variable i is never increased.
Try this code:
public static int[] sortlowhigh(int a[])
{
int i = 0;
int j = 0;
int temp;
while(j< (a.length -1) ){
i = 0;
while(i< (a.length - j - 1)){
if (a[i] > a[i+1]){
/* store low value in temp*/
temp = a[i];
/* assign low value to be the higher value*/
a[i] = a[i+1];
/* assign the old higher value to be the lower value stored in temp*/
a[i+1]=temp;
}
i++;
}
j++;
}
return a;
}
In the sortlowhigh while loop you have i, i < a.lenght is the condition of the second loop and it will continue until i is >= a.length but i never changes it always stay 0.
/*change your code as given*/
public static int[] sortlowhigh(int a[]){
int i = 0;
int j = 0; int temp=0;
while(j<(a.length-1))
{
i=0;
while(i<a.length-j-1)
{
if(a[i]>a[i+1])/* For descending order use < */
{
temp = a[i];
a[i]=a[i+1];
a[i+1] = temp;
}
i++;
}
j++;
}
return a;
}
you should reset the value of i, when the value of j is incremented.
The array is of size 3. but the value of i is already 3. so it gets garbage value in a[i+1].
Hope this helps. I haven't tried the code.

Why my selection sort doesn't sort at all?

I am trying to run selection sort to see how it work and apparently, the code that I have doesnt work as expected, can someone help me point out what i did wrong?
I know the thing goes wrong at swapping part, but i am not sure why.
public class SortingAlgorithm
{
private long timeRun;
public SortingAlgorithm()
{
timeRun = 0;
}
public long getTimeRun()
{
return timeRun;
}
public void setTimeRun(long timeRun)
{
this.timeRun = timeRun;
}
private void swap(int a, int b, int[] arrB)
{
int temp = arrB[a];
arrB[a] = arrB[b];
arrB[b] = temp;
}
public int[] selection(int[] arr, int length)
{
long startTime = System.nanoTime();
for(int i= 0; i<length-1; i++)
{
for(int k = i+1; k<length; k++)
{
if(arr[i] > arr[k])
{
swap(arr[i], arr[k], arr);
}
}
}
timeRun = System.nanoTime() - startTime;
return arr;
}
}
Here is the driver:
import java.util.*;
public class Driver
{
private static int length = 10;
private static int[] arr = new int [length];
public static void main(String [] args)
{
Random rand = new Random();
//seed the array
for(int counter = 0; counter < length ;counter++)
{
arr[counter] = rand.nextInt(10);
}
SortingAlgorithm tool = new SortingAlgorithm();
arr = tool.selection(arr, length);
for(int i = 0; i < length ;i++)
{
System.out.println(arr[i]);
}
System.out.println(tool.getTimeRun());
}
}
When you call swap, you pass in array elements:
swap(arr[i], arr[k], arr);
But your function expects the indexes to the array. You should be invoking it like this:
swap(i, k, arr);

How to write an efficient Fibonacci summing algorithm

Project Euler, problem 2: Determine the sum of the even numbers in the Fibonacci sequence up to 4 000 000. First I tried to
use a recursive algorithm for the sequence but I realized I dont have all the time in the world so I now use an iterative. It is still
extremely slow. Can I improve my code?
public class Euler2Correct {
public static int Fibonacci(int j){
/**
* Metod for returnerning number [I]j[/I] in the sequence.
*
*/
if(j<=1){
return 1;
}
else if(j==2){
return 2;
}
int tmp;
int a=2;
int b=1;
for(int k=3; k<=j; k++){
tmp=a+b;
b=a;
a=tmp;
}
return a;
}
public static void main(String[]args){
int s=0;
for(int i=2; i<4000000; i=i+3){ //Every three number is even
s = s + Fibonacci(i);
}
System.out.println(s);
}
}
You are recalculating the Fibonacci number over and over again from scratch. If you keep the running total in the Fibonacci method, you can use the previous results to prevent doing all that extra work.
Here's the modified version of your code, I tried to keep it as similar as possible
public class Euler2Correct {
public static int Fibonacci(int j) {
int tmp;
int a = 2;
int b = 1;
int total = 0;
do {
if(isEven(a)) total +=a;
tmp = a + b;
b = a;
a = tmp;
} while (a < j);
return total;
}
private static boolean isEven(int a) {
return (a & 1) == 0;
}
public static void main(String[] args) {
// Notice there is no more loop here
System.out.println(Fibonacci(4_000_000));
}
}

Categories

Resources