SetOperations - /* * Name: Amy Hoover * Assignment:...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
/** * Name: Amy Hoover * Assignment: Homework 2 * Class: COT 3100H * Date: 1/22/07 */ import java.util.*; i public class SetOperations { //Declares several program constants public static final int DEFAULT = -2; public static final int END_OF_STRING = -1; //Empty constructor public SetOperations() { } //Returns the sorted array from static method Arrays.sort() public static int [] sort(int [] A) { //Returns null if input is null if(A== null || A.length == 0) return null; //Sorts using Arrays Arrays.sort(A); //Returns sorted array return A; } //Takes two sets and returns their union public static int [] union (int[] A, int[] B) { //Checks to make sure both arrays have elements before accessing them if(A == null || A.length == 0) return sort(removeDuplicates(B)); if(B == null || B.length == 0) return sort(removeDuplicates(A)); //Sorts A and B and removes duplicates A = sort(removeDuplicates(A)); B = sort(removeDuplicates(B)); //Declares an array to hold the union of the sets int [] or = new int [A.length + B.length]; //Populates the union array for(int i= 0; i < A.length + B.length; i++) { if(i < A.length) or[i] = A[i]; else or[i] = B[i - A.length ]; } //Returns the sorted array with duplicates removed
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
return sort(removeDuplicates(or)); } //Takes two sets and returns an array of the intersecting elements public static int [] intersection (int[] A, int[] B) { //Checks to make sure both arrays have elements before accessing them if(A == null|| A.length ==0 || B== null || B.length ==0) return null; //Declare array to hold intersection int [] and; //Sorts A and B and removes duplicates A = sort(removeDuplicates(A)); B = sort(removeDuplicates(B)); //Sets and's max length to the smaller set's length if (A.length > B.length) { and = B; } else { and = A; } //Keep track of index to put element in and array int indexAnd = 0; //Checks to see if the element in A is in B for(int i = 0; i < A.length; i++) { //Declares found flag
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This document was uploaded on 09/16/2011.

Page1 / 7

SetOperations - /* * Name: Amy Hoover * Assignment:...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online