Need advice with sorting arrays

Okay, so i am trying to make this program which allows a user to input numbers in a random order, and then the program must put the numbers in order!
Here is what I have atm, I am completely stuck at this point.

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

int main () {

int *point,counter,temp;
cout<<"You may enter 5 numbers!"<<endl;

point= new (nothrow) int[5];
for ( counter=0; counter<5; counter ++) {
	cout<<"Please enter a number : "<<endl;
	cin>>point[counter];
}
cout<<"The numbers that you have inputed are :"<<endl;
for (int counter=0; counter<5; counter++){
	cout<< point[counter] << ", ";
}


for (counter=0; counter<5; counter ++) {
	if ( point[counter] > point[counter + 1]) {
		temp = point[counter];
		point[counter]=point[counter + 1];
		point[counter + 1] = temp;
		
	}

}


return 0;
}
Last edited on
Howdy. First of all I don't see a need to use dynamic allocation for the array. But that's no big deal.. except you forgot to deallocate the array with delete []. So be wary of that.

There are lots of sorting algorithms that people use to sort arrays and whatnot. Probably the simplest for you to start with (and one it seems you've started working out) is the bubble sort.

What your program does right now is go through the list once and compare each value with the one before it, and if the one before it is bigger than the one after, then you switch them.

This is a terrific start and you're actually almost there. Imagine 5 numbers:

8, 5, 4, 6, 1

Your code so far would change this list to this:

5, 4, 6, 1, 8

Doesn't seem too different? Well try running your code on the new list:

1st iteration: 5, 4, 6, 1, 8
2nd: 4, 5, 1, 6, 8
3rd: 4, 1, 5, 6, 8
4th: 1, 4, 5, 6, 8

See how that worked out? Your code is actually pretty close you just need to set it up to do that little for loop enough times.

I'll leave it to you to figure out how to make it iterate multiple times and how many times will be necessary. But if you get stuck you can probly just check out Wikipedia or something for "Bubble Sort."

You should check out other sorting algorithms too. I think they're pretty interesting!

good luck!

P.S. I didn't test that iteration stuff with a compiler because I don't have one right now and I did it in my head... so if it's wrong don't hate :P.

Topic archived. No new replies allowed.