Sorting Arrays

How to find the two greatest values of an array.

Page 1 of 1

1 Replies - 942 Views - Last Post: 25 November 2009 - 07:16 AM Rate Topic: -----

#1 jpfluege  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 05-November 09

Sorting Arrays

Post icon  Posted 24 November 2009 - 09:03 PM

Hey I have a question that I can't find in any other forums. How do you find the two greatest values of an array and print out their index's? I have no idea where to begin to do this but here is my guess.
int max(int x, int y, int z)
{
 int a[3] = {x, y, z};
 int i, g, size;
 int greatest, greatest2;
 size = 3;
 g = 0;
 for (i=0; i<size; i++)
 {
  if (g < a[i])
   g = a[i];
 }
 greatest = g;
 g = 0;
 for (i=0; i<size; i++)
 {
  if (g < a[i] && a[i] != greatest)
   g = a[i];
 }
 greatest2 = g;
 printf("Two greatest integers are %d and %d", greatest, greatest2);
}



Is This A Good Question/Topic? 0
  • +

Replies To: Sorting Arrays

#2 Ancient Dragon  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 82
  • View blog
  • Posts: 679
  • Joined: 19-July 09

Re: Sorting Arrays

Posted 25 November 2009 - 07:16 AM

The easiest way IMHO would be to create two arrays, one is an array of the numbers, and the other and array of their index values (0, 2, ...n). Sort the array of numbers, when you want values you swap them in both arrays. There are other ways to do this, one of them is to use a structure that contains both the value and index.
#include <iostream>
using namespace std;

int max(int x, int y, int z)
{
	int a[] = {x,y,z};
	int index[3] = {0,1,2};
	for(int i = 0; i < 2; i++)
	{
		for(int j = i+1; j < 3; j++)
		{
			if( a[i] > a[j])
			{
				int t = a[i];
				a[i] = a[j];
				a[j] = t;
				t = index[i];
				index[i] = index[j];
				index[j] = t;
			}
		}
	}
	printf("The two greatest values are %d (%d) and %d (%d)\n", 
		a[1], index[1], a[2], index[2]);
	return 0;

}

int main()
{
	max(23,1,3);
}


This post has been edited by Ancient Dragon: 25 November 2009 - 07:18 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1