## Finding Mean Value Of An Integer Array In Java

In Basic Algebra, mean is nothing but just an average of all the points and is calculated as a sum of all the numbers divided by the total count. Don’t be surprised if you are asked to write a java program that can calculate mean value of an array of integers.

The interviewer might be trying to test your coding style, clean coding ability and ability to think about the boundary conditions and user errors. As you can see in the program below, I have written the method to be fail proof from null value or an empty integer.

```package com.icodejava.blog.datastructure;

import java.util.Arrays;

/**
* @author Kushal Paudyal
* www.icodejava.com
* Created On -  Feb 21, 2014
*
* This class can be used to find the mean value in an array
*/
public class AlgebraMeanFinder {

public static void main(String args []) {
int [] numbers = {5,5,7,2,3,9,8,9,2,6,7,8,1};
/**
* Finding mean number of a valid integer array
*/
findMeanValue(numbers);

/**
* Testing for null array
*/
findMeanValue(null);

/**
* Passing an empty array
*/
findMeanValue(new int[] {});
}

/**
* @param numbers - array of numbers whose mean has to be found
* Mean is a simple average value of all numbers.
* This method is capable of handling boundary conditions.
*/
public static double findMeanValue(int[] numbers) {

double sum = 0;
if (numbers == null || numbers.length < 1) {
System.out.println("\nInvalid Input. Returning 0. Input was:" + Arrays.toString(numbers));
return sum;
}

for (int index = 0; index < numbers.length; index++) {
sum += numbers[index];
}

double mean = (sum / numbers.length);
System.out.println("\nInput Array is: " + Arrays.toString(numbers));
System.out.println("Sum:" + sum + " Count:" + numbers.length + " Mean Value is: " + mean);

return mean;

}

}
```

Here is the output of this program.

```
Input Array is: [5, 5, 7, 2, 3, 9, 8, 9, 2, 6, 7, 8, 1]
Sum:72.0 Count:13 Mean Value is: 5.538461538461538

Invalid Input. Returning 0. Input was:null

Invalid Input. Returning 0. Input was:[]
```

## How to intersect two sets in Java using java.util.Set data structure.

Set Intersection

Set is a collection that holds non-duplicate data. Set itself is an interface and has several implementing classes. Here are some know implementation of Set.

• AbstractSet
• ConcurrentSkipListSet
• CopyOnWriteArraySet
• EnumSet
• HashSet
• JobStateReasons
• TreeSet

In the example below, I have used HashSet to create two different sets. One set contains the name of all the developers of a fictitious team. Another set contains names of all the tech leads for that team. We are intersted to know what all tech leads are also developers. This can be done by doing an intersection of two sets. Intersection of sets can be done by calling retainAll() method as show below.

```package com.icodejava.blog.datastructure;

import java.util.HashSet;
import java.util.Set;

/**
* @author Kushal Paudyal
* www.icodejava.com
*
* Created on: 02/19/2014
*
*/
public class SetIntersection {

public static void main(String args [] ) {
/**
* Prepare a set of Developers
*/
Set<String> developers = new HashSet<String>();

System.out.println("Developers: " + developers.toString());

/**
* Prepare a set of Tech Leads
* Note that some of the items added are duplicates.
* Set does not allow duplicates which is apparent console print.
*/

/**
* To do set intersection, you can call retainAll() method
* and pass another set as parameter.
*/

System.out.println("Tech Leads who are also developers:" + developers);

}

}
```

Here is the output of this program:

```Developers: [Kushal, Pradip, Madan, Nick]
Tech Leads who are also developers:[Kushal, Nick]
```

## Bubble Sorting An Integer Array In Ascending and Descending Order

Bubble Sort Working

Bubble Sort Definition:
Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.

Complexity:
Worst Case: O(n^2) – reverse ordered list
Best Case: O(n) – fully sorted list

Note:

• Bubble Sort is not a good solution if you have a large number of items to be sorted. This is due to the time Complexity.
• Bubble Sort can however be used to quickly find if a list is already sorted.

Below is my java implementation of Bubble Sort algorithm. I have provided methods to do sorting in both ascending and descending order. This program sorts an integer array, although it can also be extended to do sorting for doubles and floats.

```package com.icodejava.blog.datastructure;

/**
* @author Kushal Paudyal
* www.icodejava.com
* Created On - Feb 18, 2014
*/
public class BubbleSortInteger {

public static void main(String args[]) {
int[] unsortedArray = { 6, 5, 2, 5, 6, 3, 4, 2, 7, 8, 9, 0 };
printArray("Unsorted Array:", unsortedArray);

int[] sortedArray = bubbleSortAscending(unsortedArray);

printArray("Sorted Array (Ascending):", sortedArray);

sortedArray = bubbleSortDescending(unsortedArray);

printArray("Sorted Array (Descending):", sortedArray);

}

private static int[] bubbleSortDescending(int[] unsortedArray) {

for (int index = unsortedArray.length - 1; index > 0; index--) {
for (int bubbleIndex = 0; bubbleIndex < index; bubbleIndex++) {

if (unsortedArray[index] > unsortedArray[bubbleIndex]) {
swap(unsortedArray, index, bubbleIndex);
}

}
}

return unsortedArray; // which is now sorted
}

private static int[] bubbleSortAscending(int[] unsortedArray) {

for (int index = unsortedArray.length - 1; index > 0; index--) {
for (int bubbleIndex = 0; bubbleIndex < index; bubbleIndex++) {

if (unsortedArray[index] < unsortedArray[bubbleIndex]) {
swap(unsortedArray, index, bubbleIndex);
}

}
}

return unsortedArray; // which is now sorted
}

private static void swap(int[] unsortedArray, int firstIndex, int secondIndex) {
if (unsortedArray == null || firstIndex < 0 || firstIndex > unsortedArray.length
|| secondIndex < 0 || secondIndex > unsortedArray.length) {
return;
}
int tempInteger = unsortedArray[firstIndex];
unsortedArray[firstIndex] = unsortedArray[secondIndex];
unsortedArray[secondIndex] = tempInteger;

}

private static void printArray(String string, int[] array) {

if (array != null && array.length > 0) {
System.out.print(string + " ");
for (int i = 0; i < array.length; i++) {
System.out.print((i > 0 ? "," : "") + array[i]);
}
}

System.out.println();

}

}
```

The out of running above program:

```Unsorted Array: 6,5,2,5,6,3,4,2,7,8,9,0
Sorted Array (Ascending): 0,2,2,3,4,5,5,6,6,7,8,9
Sorted Array (Descending): 9,8,7,6,6,5,5,4,3,2,2,0
```