Using Swap Function in an Array

Mar 16, 2014 at 6:55pm
The idea is to make an array and have it sort the contents inside the array in order from smallest to greatest by using a swap function. I don't know why it needs to be done this way when a sort function makes the most sense, but it is what it is.

For simplicity I want my array to only include three numbers. I was thinking {18,-2,24}. My only problem is that I am not understanding how to translate the swap function in an array. I tried using my previous swap function from another assignment and translate it to work for an array, but it doesn't work and I am completely lost and stuck.

Any help and explanation of how to go about doing this code would be GREATLY appreciated. I never use websites for help, but I've never been stuck like I am now (i.e. desperate times call for desperate measures).

What I tried to do was this:

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
34
35
36
37
38
39
#include <iostream>
#include <cstdlib>
using namespace std;

const int SIZE = 3;
double myList[3] = {18, -2, 24};

void swap(myList[0], myList[1], myList[2])
{
	double temp;
	if (myList[0] > myList[1])
	{
		temp = myList[0];
		myList[0] = myList[1];
		myList[1] = temp;
	}
	
	if (myList[1] > myList[2])
	{
		temp = myList[1];
		myList[1] = myList[2];
		myList[2] = temp;
	}
	
		if (myList[0] > myList[1])
	{
		temp = myList[0];
		myList[0] = myList[1];
		myList[1] = temp;
	}
}


int main()
{
	cout << myList[i] << " ";
}
return 0;
}
Last edited on Mar 16, 2014 at 6:59pm
Mar 16, 2014 at 11:57pm
Several things:

1.) You have const int SIZE = 3 on line 5, but you never use it.

2.) Nitpicky, but why is the array an array of doubles?

3.) Your swap() argument list makes no sense. I would pass an array, and then an integer type to represent the number of elements.

void swap(int array[], const unsigned short size) {

4.) I don't know why there's confusion regarding the difference between swap and sort. In a way, there is no difference, because you are sorting the array by swapping the elements.

5.) Ideally, the swap (or sort) function should work for an arbitrarily sized array.

6.) You have some weird stuff going on in main.


Here's an example of an un-optimized bubble sort function, which sorts an array by swapping the elements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void bubblesort(int array[], const unsigned short size) {
	bool sorted;
	do {
		sorted = true;
		for(unsigned short i=0; i<size-1; ++i) {
			if(array[i] > array[i+1]) {
				sorted = false;
				int temp = array[i];
				array[i] = array[i+1];
				array[i+1] = temp;
			}
		}
	}while(!sorted);
}
Last edited on Mar 17, 2014 at 12:11am
Topic archived. No new replies allowed.