Using a pointer to traverse the data items.

Lost on this assignment. Any hints would be extremely helpful!

In the following bubble sort algorithm, data is traversed using array. Please modify the code to use a pointer to traverse the data items.

 ``1234567891011121314151617181920212223242526272829303132`` `````` //bubblesort.cpp #include using namespace std; void print (const float[], const int); void sort (float[], const int); void swap (float&, float&); int main(){ float data[] = {55.5, 22.5, 99.9, 66.6, 44.4, 88.8, 33.3, 77.7}; int n = 8; print(data, n); sort(data, n); print(data, n); char c; cin >> c; return 0; } void print (const float x[], const int n){ for (int i=0; i x[j+1]) swap(x[j],x[j+1]); } ``````

The output screen should look like:
55.5 22.5 99.9 66.6 44.4 88.8 33.3 77.7
22.5 33.3 44.4 55.5 66.6 77.7 88.8 99.9
For example function

 ``1234`` ``````void print (const float x[], const int n){ for (int i=0; i

can be changed to

 ``1234`` ``````void print (const float x[], const int n){ for ( const float *p = x; p != x + n; ++p ) cout << ’\t’ << *p; cout << endl; }``````

EDIT: and it would be much better if instead of statements

 ``12`` `````` float data[] = {55.5, 22.5, 99.9, 66.6, 44.4, 88.8, 33.3, 77.7}; int n = 8;``````

there were

 ``12`` `````` const int N = 8; float data[N] = {55.5, 22.5, 99.9, 66.6, 44.4, 88.8, 33.3, 77.7};``````

in main.
Last edited on
What i've come up with so far. It compiles and outputs the correct info (is the code correct?)

 ``1234567891011121314151617181920212223242526272829303132333435`` ``````//bubblesort.cpp #include #include using namespace std; void print (const float[], const int); void sort (float[], const int); void swap (float&, float&); float *ptr; int main(){ float data[] = {55.5, 22.5, 99.9, 66.6, 44.4, 88.8, 33.3, 77.7}; int n = 8; ptr = data; print(data, n); sort(data, n); print(data, n); char c; cin >> c; return 0; } void print (const float x[], const int n) { for (const float *ptr = x; ptr != x+n; ++ptr) cout<< "\t" << *ptr; cout << endl; } void swap (float &a, float &b) { float temp = a; a = b; b = temp; } //Bubble Sort Algorithm void sort (float x[], const int n) {// sort ascending for (int i=0; i x[j+1]) swap(x[j],x[j+1]); } ``````
What is the purpose of lines 9 and 13? This variable is never used.
Topic archived. No new replies allowed.