Personally I have never heard of these, I am quite new to programming. Would like an alternative method.
the better method is the stuff you had not heard of, and you asked for a better way :) Both ideas are critical to learning, its useful to know how to do it yourself the hard way, and its critical to know the right way using the tools. I encourage you to try to follow what he did there, sooner you do, the better your code will be long term.
another way without any tools: break it down into small bits...
what it does is loop, find largest, swap largest to the end of array, repeat on array with size -1 so the old largest is excluded... over and over.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
#include<iostream>
using namespace std;
void swap(int &a, int &b) //this is built into c++ already
{
int tmp = a;
a = b;
b = tmp;
}
int max(int* ip, int size) //so is a version of this
{
int max = 0;
for(int i = 1; i < size; i++)
if (ip[i] > ip[max])
max = i;
return max;
}
int main()
{
int arr[] = { 20,8,6,5,3,12,15 };
int size = 7;
int m;
for(int i = 0; i < 3; i++, size--)
{
m = max(arr, size);
cout << arr[m] << endl;
swap(arr[m], arr[size-1]);
}
}
|
if you used the built in ones, it would be as small as furry's above code.
and, both would have the same issue: they do too much work (its not important for so small a problem). Doing it in a single iteration over the data would be better than going thru the array over and over to sort it or find max on it, etc. The only way I know to do that is to do it yourself, circling back to what I first said (you need to know how to do it yourself, and how to use built in tools for it too). Note that if you kept going for all 7 max values, it would sort the array -- this is a modified sorting algorithm.
I apologize for the awful max name reuse. Its late, and it works, but that was not good. Its also not good to use names build into the language, so swap, max, etc are troublesome. Again, its late and it was off the cuff.