# Sorting Arrays

Page 1 of 1

## 1 Replies - 990 Views - Last Post: 25 November 2009 - 07:16 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=141409&amp;s=3e4ba512eeb26f3bcf9150dbbdaa6aab&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 jpfluege

• New D.I.C Head

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

# Sorting Arrays

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

Reputation: 82
• 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