Find the smallest and second smallest

© Parineeth M R

Question 38. Find the smallest and second smallest numbers in an array


We can find the smallest and second smallest numbers in a single scan of the array. We will maintain another array called min_values for storing the 2 smallest numbers. min_values[0] will store the smallest value and min_values[1] will store the second smallest value. min_values[0] and min_values[1] are initialized to MAX_INT. As we traverse the main array, we do the following

– If the current element is smaller than min_values[0], then we move min_values[0] to min_values[1] and store the current element in min_values[0]

– If the current element is larger than min_values[0] but smaller than min_values[1], then we store the current element in min_values[1]

The code is given below:

C/C++


/*
a:input array 
length: number of elements in array a
min_value: the two smallest values will be returned here
*/
void find_two_smallest(int a[], int length, int min_value[])
{
	int i;

	min_value[0] = min_value[1] = MAX_INT;

	for (i = 0; i < length; ++i) {
		if (a[i] < min_value[0]) {
			min_value[1] = min_value[0];
			min_value[0] = a[i];
		} else if (a[i] < min_value[1]) {
			min_value[1] = a[i];
		}
	}
}



Java


/*
a:input array 
minValue: the two smallest values will be returned here
*/
public static void findTwoSmallest(int[] a, int[] minValue) {
	minValue[0] = minValue[1] = MAX_INT;

	for (int curVal : a) {
		if (curVal < minValue[0]) {
			minValue[1] = minValue[0];
			minValue[0] = curVal;
		} else if (curVal < minValue[1]) {
			minValue[1] = curVal;
		}
	}
}



Python


#a:input list 
#Return value: the two smallest values will be returned 
def find_two_smallest(a) :
	length = len(a)

	min_value = [MAX_INT, MAX_INT]

	for  cur_val in a:
		if (cur_val < min_value[0]) :
			min_value[1] = min_value[0]
			min_value[0] = cur_val 
		elif (cur_val  < min_value[1]) :
			min_value[1] = cur_val 
		
	
	return min_value[0], min_value[1]