CS210 - Algorithms and Data Structures I Department of Computer Science, NUIM T Naughton, NUIM Lab Sheet 1 Problem 1.1 int findHighest(int list[]) { /* This function returns the index of the largest int in list. ** If there are multiple occurances of this int we return the ** last occurance. If the list has no elements, return -1. */ int highestindex; // result int counter; // array iterator if (list.length = 0) { highestindex = -1; // if list is empty... } else { highestindex = 0; // assume first is highest counter = 1; // start looking from the second element while (counter < list.length) { if (list[counter] >= list[highestindex]) { highestindex = counter; } counter++; } } return highestindex; } Problem 1.2 void findDuplicates(int list[]) { /* This function prints out the indexes of the first two duplicates ** found in list. The user is notified if no duplicates are found. */ int counter; // array iterator int pdup; // a possible duplicate boolean found; // have we found duplicates yet? // check each list element in turn... counter = 0; found = false; while ((counter < (list.length-1)) && (!found)) { pdup = counter+1; while ((pdup < list.length) && (!found)) { if (list[pdup] == list[counter]) { found = true; } pdup++; } counter++; } if (found) { println("Duplicates found at indexes " + (counter-1) + " and " + (pdup-1) + '.'); } else { println("No duplicates found."); } } Problem 1.3 void findClosestTo10(int list[]) { /* This function prints out the index of the element in list ** that has a value closest to 10. If multiple such values exist, ** the first one found is printed out. */ int counter; int cindex; // index with closest value to 10 int cval; // difference between cindex's value and 10 if (list.length == 0) { println("List is empty."); } else { cindex = 0; // assume it's the first element cval = Math.abs(list[cindex] - 10); counter = 1; // start searching from the second element while (counter < list.length) { if ( Math.abs(list[counter] - 10) < cval) { cindex = counter; cval = Math.abs(list[counter] - 10); } counter++; } println("The value at index " + cindex + " is closest to 10."); } }