Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sign In with Facebook Sign In with Google Sign In with OpenID


We have migrated to a new platform! Please note that you will need to reset your password to log in (your credentials are still in-tact though). Please contact if you have questions.
Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.


R9986R9986 Posts: 2Member
This program is sorting a randomized array of integers using the bubblesort algorithm.
a) Try to understand the structure of the source code. Compile and run the program.
b) Simplify the code and correct the program. Also the program logic can be improved!
c) Modify the source code, so that the swapping of two values will be done by a function called swap values()
using call-by-reference. The function should have as arguments only the two array elements that must be
exchanged. (Note: do not pass the whole array to the function!)

We consider an array with the first element containing the number of
elements in the array, followed by 10 randomly initialized integers (elements).
The code must sort the 10 elements in ascending order.

Compile: g++ -Wall sorting.cpp -o sorting


using namespace std;

int main()
const int SIZE=10;
int s_array[SIZE];
int s_array_2[]={3,2,0,0};

bool isExchanged=true;

// We suppose that: the first element of the array contains the number
// of elements in the array, followed by 10 elements that must be sorted
s_array[0] = sizeof( s_array) / sizeof( s_array[0]);

// Read the 10 elements
for (int i=1; i<=SIZE; i++)
// rand() generates a random int value in the range [0-999]
s_array[i]= rand() % 1000;

// Output the unsorted array
cout << "UNsorted array has "<< s_array[0] <<" elements. These are:
for (int j=1; j<=10; j++)
cout<< " "<< s_array[j] <<",";
cout<< endl;

// sort the 10 array elements
while (isExchanged==true)

for (int x=1; x<=10; x++)
// exchange two elements
if (s_array[x] > s_array[x+1])
int temp=s_array[x];

// Output the sorted array
cout << "The array has "<< s_array[0] <<" elements. These are:
for (int j=1; j<=10; j++)
cout<< j << " : "<< s_array[j] <<"

// Hint: uncomment the following code in order to find mistakes ... :-)
// // Display the second array
// for (int j=0; j<=2; j++)
// {
// cout<< " "<< s_array_2[j] <<",";
// }
// cout<< endl;

return 0;
Sign In or Register to comment.