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.

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

//bubblesort.cpp
#include <iostream>
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<n; i++) cout << ’\t’ << x[i];
     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<n; i++)
          for (int j=0; j<n-i-1; j++)
               if (x[j] > 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

1
2
3
4
void print (const float x[], const int n){
     for (int i=0; i<n; i++) cout << ’\t’ << x[i];
     cout << endl;
}

can be changed to

1
2
3
4
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

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

there were

1
2
     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?)

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
//bubblesort.cpp
#include <iostream>
#include <cstring>
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<n; i++)
for (int j=0; j<n-i-1; j++)
if (x[j] > 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.