Bubble sorting with user defined amount of elements

Hi guys, my first post here.

Im writing some code to bubble sort a list of randoms numbers, 10 at the moment.
I want to be able to user input the amount of elements that would be sorted.
I think i'd have to use vector instead of arrays, but unsure how to do this.
Or, how to be able to change the size of the array.

If you could show me how to do this, it'd be greatly appreciated!

Thanks

Easty1802
newbie programmer

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
  #include <iostream>

using namespace std;
#define SIZE 10

float numbers[SIZE];
int move_n;
int i;
int place;


void bubble();
void list();


int main(void)
{
	
	
	
	
		
	for (i = 0; i < SIZE; i++){
		numbers[i] = rand() % 100 ;
	}
	


	cout << "Data in origional order:" << endl;
	list();
	
	bubble();
	
	cout << "\nData in ascending order:" << endl;
	list();

	
}


void list()
{

	for (i = 0; i < SIZE; ++i){
		cout << numbers[i] << endl;
	}

}

void bubble()
{ 
	for (move_n = 1; move_n < SIZE; ++move_n){
		for (i = 0; i < SIZE - 1; ++i){
			if (numbers[i] > numbers[i + 1]){
				place = numbers[i];
				numbers[i] = numbers[i + 1];
				numbers[i + 1] = place;
			}
		}
	}
}

@easty1802

Here is how to create an array of unknown size, at program start. I also added srand() to make sure you get different numbers with each program run. Hope this helps.

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <ctime> // For srand()

using namespace std;

void bubble(int numbers[],int);
void list(int numbers[],int);


int main(void)
{
	 srand(static_cast<int>(time(0))); // seed the random number generator
	 int SIZE;
	cout << endl << "MaxSize for the array, to equal what ? : ";
	cin >> SIZE;
	int* numbers = new int[SIZE];

	for (i = 0; i < SIZE; i++)
	{
		numbers[i] = rand() % 100 ;
	}

	cout << "Data in origional order:" << endl;
	list(numbers, SIZE);
	
	bubble(numbers, SIZE);
	
	cout << "\nData in ascending order:" << endl;
	list(numbers, SIZE);

       delete numbers;
}


void list(int numbers[], int SIZE)
{
	for (i = 0; i < SIZE; ++i)
	{
		cout << numbers[i] << endl;
	}
}

void bubble(int numbers[],int SIZE)
{ 
      int place;	
      for (int move_n = 1; move_n < SIZE; ++move_n){
		for (int i = 0; i < SIZE - 1; ++i){
			if (numbers[i] > numbers[i + 1]){
				place = numbers[i];
				numbers[i] = numbers[i + 1];
				numbers[i + 1] = place;
			}
		}
	}
}
Last edited on
Topic archived. No new replies allowed.