Call-by-reference - Programmers Heaven

Howdy, Stranger!





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:
cout<< " "<< s_array[j] <<",";
cout<< endl;

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

// 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:
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.