selection problem k=n/2

closed account (S2wbqMoL)
I have all the code, at least I think I do. I have a bubblesort to sort my numbers and a timer to see how long it takes to sort them. But when I place the pointer in the cout line to show that the numbers are sorted to solve the selection problem k=n/2. It outputs half of the original number and not half of the numbers sorted.How do I fix this??

Code:

# include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

void bubbleSort(int array[], int size)
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size - 1); count++)
{
if (array[count] > array[count + 1])
{
temp = array[count];
array[count] = array[count + 1];
array[count + 1] = temp;
swap = true;
}
}
} while (swap);
}


int main()
{
int n;
int k;
clock_t beg, end;

// prompt and read numbers into an array
cout << "A program that performs bubble sort";
cout << "\nEnter array size : ";
cin >> n;

int *prt1=new int[n];


// randomize the random number generator using current time
srand(time(0));

//insert numbers into array
for (int i=0; i<n; i++)
*(prt1 + i)= 1 + rand() % 1000;
//print the random numbers before sorting between 1 and 1000
cout << "\n\n\tThe numbers before sorting are:\n\t";
for (int i=0; i<n; i++)
cout << *(prt1 + i) << "\t";

beg=clock();
bubbleSort(prt1, n);
end=clock();

//print the sorted numbers
cout << "\n\n\tThe numbers after sorting are: \n\t";
for(int i=0; i<n; i++)
cout << *(prt1 + i) << "\t";
cout<< endl;
cout << "This solves the selecton problem for k=n/2 :" << (k = *(prt1)/2-1) << endl;
cout << endl;

cout << "\n\n\tStarting click: " << beg << "\n\tEnding click : " << end;
cout << "\n\n\tTime taken Bubble Sort : " << ((end-beg)*1.0) / CLK_TCK << " seconds";

delete[] prt1;

cout << "\n\n\t";
system ("pause");

return 0;
}
C++ has a neat syntax feature called the offset operator: *(ptr+x)==ptr[x]

I don't think I understand what you're trying to do. What do you want to output? prt1[1..n/2]? prt1[n/2]?

PS: It's "ptr". "Poinret" is not a word.
Last edited on
closed account (S2wbqMoL)
My output should be the number that is in the n/2 (halfway) spot in the sorted list. Yes, I am probably the worst typing student in computer engineering program.
In that case prt1[n/2] is the element you need to print.
closed account (S2wbqMoL)
Thank you Helios. That seemed to do the trick. I appreciate it.
closed account (S2wbqMoL)
One last problem which I just found out from another student in class. How do I change the timestamp to milliseconds. Right now it is timing the clicks in seconds, I need to be able to change it into milliseconds??? Thanks in advance.
You are dividing by CLOCKS_PER_SEC (or CLK_TCK. Whatever that is). Don't.
Topic archived. No new replies allowed.