Finding second largest number in an array

c programming

  • (2 Pages)
  • +
  • 1
  • 2

16 Replies - 17730 Views - Last Post: 04 October 2009 - 01:01 AM Rate Topic: -----

#16 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon


Reputation: 6996
  • View blog
  • Posts: 14,635
  • Joined: 16-October 07

Re: Finding second largest number in an array

Posted 03 October 2009 - 05:14 PM

You know, this has proven way more annoying than in initially appeared. :P

This is overkill, but I know it will work.
#include <stdio.h>
#include <stdlib.h>

int first_largest(const int *a, int size) {
	int i, i_first=0;
	
	for(i=1; i<size; i++) { 
		if(a[i_first] < a[i]) { i_first = i; }
	}
	return i_first;
}


int second_largest(const int *a, int size) {
	int i, i_first, i_second;
	
	i_first = i_second = first_largest(a, size);
	
	for(i=0; i<size; i++) {
		if(a[i_first]!=a[i] && (i_first==i_second || a[i_second] < a[i])) {
			i_second = i;
		}
	}
	return i_second;
}

void printArray(int *p, int size) {
	while(size-- > 0) {
		printf("%d ", *p);
		p++;
	}
}

void test(int *a, int size) {
	printArray(a, size);
	printf(" : second_largest = %d\n", a[second_largest(a, size)]);
}

#define A_SIZE 4
int main() {
	int a[A_SIZE] = {2,4,6,8};
	int b[A_SIZE] = {44,44,22,11};
	int c[A_SIZE] = {20,33,25,10};
	int d[A_SIZE] = {1,2,4,4};
	
	test(a, A_SIZE);
	test(b, A_SIZE);
	test(c, A_SIZE);
	test(d, A_SIZE);
	
	return 0;
}


Was This Post Helpful? 0
  • +
  • -

#17 brac589  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 04-March 09

Re: Finding second largest number in an array

Posted 04 October 2009 - 01:01 AM

Who knew a simple C program could giver you such trouble.
ahaha

Thanks for your help guys.

I believe it just might be working now.
I will only be able to tell once i test all the different inputs.:P

This post has been edited by brac589: 04 October 2009 - 01:02 AM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2