Home > IB Computer Science 2017 > Array algorithms practice

Array algorithms practice

You will often get questions from me in the form: Write an algorithm that takes [argument(s)] and returns [return value]. In your Paper 1, you may be asked to do this in pseudocode, and you will need to be able to do this. However, I like you to be able to test your algorithms by running them, hence I will ask you to implement them in Java. Below is a template for an ArrayAlgorithms class, that you can copy into Netbeans, and then use to test out your algorithms.

  1. Write an algorithm print that takes an array of integers and prints them out in a friendly way like this:
    [0] 6432
    [1] 2725
    [2] 7255
    etc
  2. Write an algorithm max that takes an array of integers and finds the largest.
  3. Write an algorithm sum that takes an array of integers and returns the sum.
  4. Write an algorithm thresholdCount that takes an array of integers a[] and an int threshold and returns the number of elements in a[] that are greater than or equal to threshold.
  5. Write an algorithm threeHighest that takes an int array and returns an array of its three highest elements.
  6. Write an algorithm reverseCopy that takes an int array and returns a copy of the same array with its numbers reversed.
  7. Write an algorithm reverseInPlace that takes an int array and reverses its numbers, returning void.
package arrayalgorithms;
import java.util.Random;

/**
 *
 * @author robertsonj
 */
public class ArrayAlgorithms {
    public static void main(String[] args) {
        int[] a = new int[100];
        Random r = new Random();
        for (int i = 0; i < 100; i++){
            a[i] = r.nextInt(10000);
        }
        ArrayAlgorithms alg = new ArrayAlgorithms();

        // Call your algorithm functions here...
        int x = alg.exampleAlgorithm(a);
        System.out.println(x);
    }
    
    int exampleAlgorithm(int[] array){
        // This is a dummy algorithm.
        // It just shows you how to pass an array to a function and return some value.
        return 3;
    }
    
    // Add new algorithms here.
    // ...
}

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s