I have assignment to complete the following coding. My lecturer only give the number of rows and the variables used. I was asked to fill out the program itself, to sort the data using the bubble sort and then find the median value. This program uses a pointer, and I am still confused to use it. I've tried but still not working. I think my mistake was laying of variabel *x in the main. Please help me, where is my mistake? thank you very much :)
Yes, this is an error. Variable of type pointer holds a memory address. Dereferencing a pointer accesses the value in the memory in the address that the pointer has. In this short example line 1 creates a pointer variable but does not set its value. The x does not hold any valid address. Then, in line 2 we try to write 42 into the memory location that we have no idea about.
Your swap and bubblesort do both test val1 < val2. Are you sure that is appropriate and logical?
Your median is equivalent to:
1 2 3
void median(int *array, int size){
array[0] = array[size/2];
}
That is not what one expects from such function. How about returning a value from that function?
It is not clear, which parts of your code have been written by your lecturer and what is your contribution.
#include <iostream>
#include <cstdlib>
#include <iomanip>
#define max 10
usingnamespace std;
void swap(int *x, int*y)
{
…………………………………;
if (…………………………………)
{
…………………………………;
…………………………………;
…………………………………;
}
}
void bublesort (int *array, int size)
{
for (…………………………………)
{
for(…………………………………)
{
…………………………………
…………………………………
}
}
}
void ……………………………;
{
……………………………;
}
int main()
{
int *x;
int ……; //var for the number of data entered
cout << "The number of data to be entered? ";
cin >> ……………………………;
cout << "Enter data\n";
……………………………
{
……………………………;
cin >> ……………………………;;
}
//show the data
cout<<"Data before sorted : "<<endl;
……………………………;
{
……………………………;
}
//call sort function
……………………………;
cout<<endl;
cout<<"Sorting in ascending"<<endl;
……………………………;
{
……………………………;;
}
cout<<endl;
//call median function
……………………………;
return 0;
}
He only give *x as a variable that holds the number.
I'm not sure I'm allowed to add another variable. If it should stay that way, then how?
That does give the impression that the main() should allocate memory dynamically for the array, but there are no placeholders for the new and corresponding delete [].
The median function does not return a value. Therefore, it ought to show the median. Btw, if 'size' is even, then http://en.wikipedia.org/wiki/Median
I have a feeling that the condition in swap() is to prevent swap of item with itself.