2
People I’m reading book "Programming Principles and Practice using c++ (2nd Edition)" from C++ creator. There is an exercise there at the very beginning talking to do a program that sorts the data numbers. I did it using Bubblesort, burned a lot of neurons doing more I think I got. I wanted to know if he has any error or some situation that wrong, I did some tests and it seems to work. Thank you.
Code below.
#include <iostream>
using namespace std;
void bubbleSort(int * my_integer_array_pointer /*pointer to original array*/,unsigned int array_size)
{
int tempChanger = 0;
unsigned int Swaps = 0;
unsigned int i = 0;
for (i = 0; i < (array_size -1); i++) //iterate "my_integer_array_pointer", "array_size-1" times
{
if (*(my_integer_array_pointer+i) > *(my_integer_array_pointer+i+1)) // if left number is greater than right number, swapp then
{
tempChanger = *(my_integer_array_pointer+i);
*(my_integer_array_pointer+i) = *(my_integer_array_pointer+i+1);
*(my_integer_array_pointer+i+1) = tempChanger;
Swaps++; //count the number of swapped numbers
}
}
if (Swaps > 0) // if swap more than 0 times, need to iterate list again
{
bubbleSort(my_integer_array_pointer,array_size);
}
/*
else = list is already sorted, stop function.
*/
}
int main()
{
cout << "Please type the amount of numbers you want to sort:" << endl;
int my_integer_array_size;
cin >> my_integer_array_size;
int my_integer_array[my_integer_array_size] = {};
for (int i = 0; i < my_integer_array_size; i++) //iterator used to assign a value to each element of "my_integer_array" with "cin"
{
cout << "Please type the " << i+1 << " number" << endl;
cin >> my_integer_array[i];
}
cout << endl;
bubbleSort(my_integer_array,my_integer_array_size);
cout << "The ordered array is below :" << endl;
for (unsigned int i = 0; i < sizeof(my_integer_array) / sizeof(int); i++) //iterator to show the results
{
cout << my_integer_array[i] << endl;
}
return 0;
}