sort function

Dec 1, 2016 at 5:33pm
I have a project due soon and im confused on the sort function. i have the sort function from my book and i would like to put it in descending order for any array.

void sort(double x[], int n)
{
int m;
double hold;
for (int k = 0; k <= n-2; ++k)
{
m = k;
for (int j = k + 1; j <= n - 1; ++j)
{
if (x[j] < x[m])
m = j;
}
hold = x[m];
x[m] = x[k];
x[k] = hold;
}
return;
}
Dec 1, 2016 at 6:30pm
Given this code:
1
2
3
4
5
6
m = k;
for ( int j = k + 1; j <= n - 1; ++j )
{
  if ( x[j] < x[m] )
    m = j;
}

What can you say about the value of element x[m] after the loop?
Is it bigger, smaller, median, random, or what?
What decides how the m is chosen?
Last edited on Dec 1, 2016 at 6:31pm
Dec 2, 2016 at 1:41am
Hey bud. I too have a project due next week that involves sorting. I struggled for a while, but then I learned there is a std library function called sort. Check out this link, there's a lot in there, but look for what you're trying to do and plug in what you need!

http://www.cplusplus.com/articles/NhA0RXSz/
Dec 2, 2016 at 7:42am
WhatAml wrote:
Check out this link, there's a lot in there, but look for what you're trying to do and plug in what you need!

It is very obvious that the OP has to create his/her own sort function. Even if he/she could, you are not being much of a help. All you do is give the OP a link to an article. A reference would have been better (simpler): http://www.cplusplus.com/reference/algorithm/sort/

std::sort() is also simple to explain so you could've easily explained yourself with an example.

Anyways, here you go OP (assuming you're using bubble sort):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void sort(double array[], const unsigned int SIZE)
{
	for (unsigned int rep = 0; rep != SIZE; ++rep)
	{
	    const unsigned int SWAP_SIZE = SIZE - 1;
	    
		for (unsigned int index = 0; index != SWAP_SIZE; ++index)
		{
		    const unsigned int FIRST = index, NEXT = FIRST + 1;
		    
			if (array[FIRST] < array[NEXT])
			{
			    const double TEMP = array[FIRST];
			    
			    array[FIRST] = array[NEXT];
			    array[FIRST] = TEMP;
			}
		}
	}
}
Last edited on Dec 2, 2016 at 7:43am
Topic archived. No new replies allowed.