my sorting program doesn't work

Problem solved!
Last edited on
idkhowtouse wrote:
Hello, it's an exchange sort program and when I run it, it isn't sorted. Can you give me any hints?

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
32
33
#include <iostream>
using namespace std;

void swap(int x, int y)
{
	int temp = x;
	x = y;
	y = temp;
}

void exchangeSort(int n, int S[])
{
	int i, j;
	for (i = 1; i <= n - 1; i++)
		for (j = i + 1; j <= n; j++)
			if (S[j] < S[i])
				swap(i, j);
}

int main()
{
	int i;

	int S[] = { 10, 5, 3, 7, 21, 15, 2, 11, 4, 20 };

	exchangeSort(10, S);

	for (int i = 0; i < 10; i++)
		cout << S[i] << "  ";

	system("pause");
	return 0;
}

Array indices start counting from zero.
Last edited on
You should pass a pointer or reference to your swap function.
firstly, you should pass pointer or reference if you want to exchange two via, so it looks like
 
void swap(int& i, int& j)


secondly, array's index is start from zero and end at (length-1), so

1
2
3
4
	for (i = 0; i <= n - 1; i++)
		for (j = i + 1; j <= n; j++)
			if (S[j] < S[i])
				swap(S[i], S[j]);


then, it works!
You're passing by value instead of passing by reference or pointer. When you pass by value, a local copy of the argument variable is created which would cease to exit the moment the function terminates. By passing by reference or pointer, you can give the function direct access to the argument variable. You may also use the const keyword when you're passing by reference or pointers to restrict what the function can do with the variables being passed to it.

Lastly, don't get into the habit of using 'or equal to' in your loops. Instead, always make sure that your loops are counting from index 0 onward.
Thank you everyone!
Please don't delete your post. It makes this thread useless as a learning resource for others. Please respect the other users of this forum, and restore your original post.
Topic archived. No new replies allowed.