Selection Sort [ARRAY]

This code work, but I firgue the style is very inefficient. As a good programmer, a decent style of writing is significant. Any good suggestions from experts? Does it have a huge memory leak?

int main ( )
{
	int data [] = { 7, 3, 9, 2, 5};
	int tmp;

	for( int i = 0; i < 5; i++)
		cout << data[i] << " "; 

	cout << endl;

	for (int i = 0; i < 5 -1; i++)

		for (int j = i+1; j < 5; j++)

			if (data[i] > data[j])
			{
				tmp = data[i];
				data[i] = data[j];
				data[j] = tmp;
			}

	for( int i = 0; i < 5; i++)
		cout << data[i] << " "; 

	cout << endl;
	system ("pause");
	return 0;
}





7 3 9 2 5
2 3 5 7 9
Press any key to continue . . .
Last edited on
You aren't dynamic allocating anything, ¿how it could leak?

1
2
3
4
5
6
7
8
template <class Iter>  //arrays and others containers (like list, vector, deque, ...)
void selection_sort(Iter begin, Iter end){ //range [)
  for(; beg!=end; ++beg)
    std::swap(
      *begin, 
      *std::minimum_element(begin, end)
    );
}
1_ Modularise (you could use a print function too)
A_ Generalise (avoid magic numbers, allow any type, allow different containers)
∝_ Don't use system
____system is evil http://www.cplusplus.com/forum/articles/11153/
____keeping the console open http://www.cplusplus.com/forum/articles/7312/

About your algorithm, when finding the minimum just keep the index. That way you just do one swap per iteration (the copies could be expensive)

Regards
Topic archived. No new replies allowed.