Qualcomm Interview Question
Software Engineer / Developersvoid largest_two(int a[], int b[] )
{
int i;
for (i=0;i<9;i++) {
if (a[i] > b[0] ) {
b[0] = a[i];
}
if (a[i] > b[1] && a[i] < b[0])
b[1] = a[i];
}
}
void main() {
int a[10];
int b[2];
int i;
for (i=0;i<9;i++)
a[i] = random();
largest_two(a,b);
for (i=0;i<9;i++)
printf("a[%d]=%d \n",i, a[i]);
printf("\n");
for (i=0;i<2;i++)
printf("b[%d]=%d \n",i, b[i]);
}
bool largest_two( int a[], int arraySize, int *largest, int *secondlargest)
{
if( !arraySize ) return false; /* Empty array */
*largest = *secondlargest = a[0];
for( i = 0; i < arraySize; i++ )
{
if( *largest < a[i] )
{
*secondlargest = *largest;
*largest = a[i];
}
}
return true;
}
int two_max (int *array, int size, int *first, int *second)
{
int i;
if (array == NULL && first == NULL && second == NULL && size < 2) return 0;
*first = a[0];
for (i = 1; i < size; i++)
{
if (*first <= a[i])
{
*second = first;
*first = a[i];
}
}
return 1;
}
int two_max (int *array, int size, int *first, int *second)
{
int i;
if (array == NULL && first == NULL && second == NULL && size < 2) return 0;
*first = a[0];
for (i = 1; i < size; i++)
{
if (*first <= a[i])
{
*second = first;
*first = a[i];
}
else if(*second <= a[i])
{
*second = a[i];
}
}
return 1;
}
int two_max (int *array, int size, int *first, int *second)
{
int i;
if (array == NULL && first == NULL && second == NULL && size < 2) return 0;
*first = a[0];
for (i = 1; i < size; i++)
{
if (*first <= a[i])
{
*second = first;
*first = a[i];
}
else if(*second <= a[i])
{
*second = a[i];
}
}
return 1;
}
void computeMaxnSecondMax(int* arr, int* max, int* secondMax)
{
int i = 0;
if(arr[0]>arr[1])
{
*secondMax = arr[1];
*max = arr[0];
}
else
{ *secondMax = arr[0];
*max = arr[1];
}
for(i=2;i<6;i++)
{
if(arr[i]>*max)
{
*secondMax = *max;
*max = arr[i];
}
else if(arr[i]>*secondMax)
{
*secondMax = arr[i];
}
}
}
I came up with some simple logic like this. It works for the arrays which I tested.
uint32_t main(void)
{
//uint32_t array[10] = {1,2,3,4,5,6,7,8,9,10};
//uint32_t array[10] = {10,9,8,7,6,5,4,3,2,1};
uint32_t array[10] = {5,3,6,1,0,8,11,4,4,10};
uint32_t largest[2] = {0};
uint32_t loopVar = 0;
printf("The Input Array is\n");
for(loopVar = 0; loopVar < 10; loopVar++){
printf("%d \t",array[loopVar]);
}
for(loopVar = 0; loopVar < 10; loopVar++){
if (array[loopVar] > largest[0]){
largest[1] = largest [0];
largest[0] = array[loopVar];
}
else if (array[loopVar] > largest[1]){
largest[1] = array[loopVar];
}
}
for(loopVar = 0; loopVar < 2; loopVar++){
printf("\n%d \t",largest[loopVar]);
}
return 0;
}
int two_max (int *array, int size, int *first, int *second)
- Karthik September 23, 2009{
int i;
if (array == NULL && first == NULL && second == NULL && size < 2) return 0;
*first = a[0];
for (i = 1; i < size; i++)
{
if (*first <= a[i])
{
*second = first;
*first = a[i];
}
else if(*second <= a[i])
{
*second = a[i];
}
}
return 1;
}