Dana Vrajitoru
C101/I210 Computer Programming

C101/I210 Homework 12

Due date: Wednesday, April 29, 2020.

Objective: To work with sorting functions for arrays in Java.

In this homework you will continue adding code to the program that sorts arrays in Java that we started in the lab. Make sure to do Lab 12 first.

Ex. 1. More Array Methods

Reopen (if you closed it) the project that you created for lab 12. Add the following features to it.

a. Duplicate Values

Write a static method that takes one parameter which is a sorted array and goes through it and prints out all the duplicate values. For that, use a for loop with an i that goes from 0 to the length of the array -2 (similar to the one we wrote in the lab) and for each position, it checks if a[i] is equal to a[i+1]. If they are, the function should output a[i]. The header of the function should be

static void findDuplicates(int[] a)

Add a call to this function in the main after you sorted the input array.

b. Unique Values

Write a static method that takes in a sorted array and outputs all the unique values. Since the array is sorted, for the values to be unique, they need to be different both from the value before them in the array and from the value after them. a[0] and a[a.length-1] are special because they only have one neighboring value. The header of the function should be

static void findUnique(int[] a)

In the function, start by comparing a[0] and a[1], and output a[0] if they are different. Then use a loop with i going from 1 to a.length-2, and for each i, if a[i] is different from both a[i-1] and a[i+1], then output a[i]. Finally, after the loop, check if a[a.length-2] is different from a[a.length-1], and if they are, output a[a.length-1].

Add a call for this function too in the main, also after the array is sorted.

Test the program to make sure all of the functions work properly.

Turn in:

Upload the lab and homework .java file (should be the same): ArraySort.java, to Canvas in Assignments - Homework 12.