Friday, April 11, 2008

Bigger than N

Write a function which, given an array and a number n, returns an array of all the numbers in the original array that are bigger than n.

Just search the array linearly and find all the elements that are bigger than n. The one tricky part is that you need to save these in an array and, depending on the language/libraries you are using, you might need to declare the size of the array first. Here I decided to first count the number of items bigger than n, then declare the array, then populate. This program must go over the array twice but only uses as much memory as needed.

A better solution would use an extensible array (ArrayList in Java).

public class BiggerThanN {
/** @param a an array of integers of length > 0
@param n
Returns an array of all a[i] for which a[i]
> n.*/
public static int[] biggerThanN(int[] a, int n){
//I don't know how many items are bigger than n so I must
//first count them so I can then create an array of the correct
int count = 0;
for (int i =0; i < a.length; i++){
if (a[i] > n) {
int result[] = new int[count];
int j = 0;
for (int i =0; i < a.length; i++){
if (a[i] > n) {
result[j++] = a[i];}}
return result;

public static void printArray(int[] a){
for (int i=0; i < a.length; i++){

//Do some unit testing
public static void main (String [] argv){
int[] a = new int[5];
a[0] = 1; a[1] = 3; a[2] = 2; a[3] = 7; a[4] = 5;

No comments: