bubblesort not passing data or doesnt work - c++

I'm writing a program for an assignment in which the program stores grades in array, has a function that inputs the grades and stores them in an array and returns the number of grades, handles up to 20 grades, has a function that sorts the array of grades, and has a separate function that takes the sorted array and returns the median. I have the code written but it is not sorting the array. Not sure what I am doing wrong. Any help would be greatly appreciated.
#include <iostream>
using namespace std;
int main();
void bubbleSort(double[], int); //Function prototypes
void swap(double &, double &);
void findMedian(double[], int, int, int, int, int);
int main()
{
int numgrades; // the number of grades in the array
double grades[20]; // array of grades
int first = 0,
last,
middle;
double medianeven; // median if # of elements are even
double medianodd; // median if # of elements are odd
bool isEven(int); // determines if the #of elements is even
cout << "Please enter the number of grades. ";
cin >> numgrades;
for (int index = 0; index <= numgrades - 1; index++)
{
cout << "Enter test score "
<< (index + 1) << ":";
cin >> grades[index];
}
void bubbleSort(double grades[], int numgrades);
for (int index = 0; index <= numgrades - 1; index++)
{
cout << grades[index];
}
(((last) = (numgrades - 1)));
(((middle) = (first + last) / 2));
if (isEven(numgrades))
{
(medianeven = ((grades[middle] + grades[middle + 1]) / 2));
cout << "The median grade is +" << medianeven << "." << endl;
}
else
{
((medianodd = grades[middle]));
cout << "The median grade is -" << (medianodd) << "." << endl;
}
return 0;
}
void bubbleSort(double array[], int numgrades)
{
int minIndex;
double minValue;
for (int start = 0; start < (numgrades - 1); start++)
{
minIndex = start;
minValue = array[start];
for (int index = start + 1; index < numgrades; index++)
{
if (array[index] < minValue)
{
minValue = array[index],
minIndex = index;
}
}
swap(array[minIndex], array[start]);
}
}
void swap(double &a, double &b)
{
double temp = a;
a = b;
b = temp;
}
bool isEven(int number)
{
bool status;
if (number % 2 == 0)
status = true;
else
status = false;
return status;
}

In main
void bubbleSort(double grades[], int numgrades);
is a forward declaration of the bubbleSort function, not a call to it.
bubbleSort(grades, numgrades);
will call the function.

Related

Function not doing anything after being called

So I am making a program that calls functions to generate random numbers. Then calls a function to print those results. The second thing I want to print is the random numbers but after they are sorted in ascending order. After some tweaking with the ascending order function for an array, I try displaying it with my print function and nothing happens
Originally it did display as a second part of the output, but it didn't work and only showed 0's. Now I think I fixed the code but now it won't even display anything in the output so I have no way to check if its working and I am really confused as to why
#include <iomanip>
#include <iostream>
#include <cstdlib>
using namespace std;
#define lowerbound 10.0
#define upperbound 950.0
#define min_values 75
#define max_values 150
#define max_val_file 40
#define max_output 12
double randDouble();
int buildRandom(double array[]);
void print(string, double array[], int);
void sort(double array[], int);
int main()
{
srand(19);
int num_vals;
double random_array[max_values];
double sorted_array[max_values];
string title1 = "Random Values";
string title2 = "Sorted Random Values";
num_vals = buildRandom(random_array);
cout << "There are " << num_vals << " values in the first array" << '\n';
print(title1, random_array, num_vals);
sort(random_array, num_vals);
cout << '\n';
print(title2, sorted_array, num_vals);
}
double randDouble()
{
int random_integer = rand();
double random_value;
random_value = lowerbound + (random_integer / (RAND_MAX / (upperbound - lowerbound)));
return random_value;
}
int buildRandom(double random_array[])
{
int num_vals = min_values + rand() % (max_values - min_values + 1);
int i;
double random_num;
for (i = 0; i < num_vals; ++i)
{
random_num = randDouble();
random_array[i] = random_num;
}
return num_vals;
}
void print(string title, double random_array[], int num_vals)
{
int i;
cout << '\n' << title << '\n' << '\n'<< setw(8);
for (i = 0; i < num_vals; ++i)
{
cout << setprecision(3) << fixed << random_array[i] << setw(9);
if ((i + 1) % max_output == 0)
{
cout << '\n' << setw(8);
}
}
}
void sort (double sorted_array[], int numberOfValues)
{
int top = 0;
int x, SSF, PTR;
double swap;
double last = numberOfValues - 1;
for (top = 0; top < last; ++top)
{
PTR = top;
SSF = top;
for (x = 0; PTR < last; ++x)
{
if (sorted_array[PTR] < sorted_array[SSF])
{
SSF = PTR;
}
}
swap = sorted_array[SSF];
sorted_array[SSF] = sorted_array[top];
sorted_array[top] = swap;
}
}

Calling a void function to sort an array in C++

I am trying to call a void function that sorts a random array from smallest to highest, then reuse that void function to sort an array that is pulled from a notes file.
I am having trouble with getting the sort function to work when I try to print from the print() function.
We just learned about recalling today, and I was trying to find a way to make that work, but couldn't wrap my head around it.
Here is the code (I apologize for all the comments, it is for a class and I'm struggling):
#include <iomanip>
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
#define LOWER_BOUND 1.0
#define UPPER_BOUND 250.0
#define MIN_VALUE 25
#define MAX_VALUE 75
#define PRINT_MAX_VALUE 12
//prototypes
double randDouble();
int buildRandom(double array[]);
int buildFile(double fileArray[]);
void print(string title, double array[], int numValues);
void sort(double array[], int numValues);
int main()
{
//declare variables
int numValues, output, fileValues;
double array[MAX_VALUE];
double fileArray[MAX_VALUE];
//seed the RNG
srand(52);
//filling numValues
numValues = buildRandom(array);
//showing numValues
cout << "You have " << numValues << " values in your array." << endl << endl;
//initial print
print("Array of Random values: ", array, numValues);
cout << endl << endl;
//sorting array
sort(array, numValues);
//sorted print
print("Array of sorted values: ", array, numValues);
//store into new array
fileValues = buildFile(fileArray);
//display fileValues
cout << endl << endl << "You have " << fileValues << " values in your second array." << endl << endl;
//print file array
print("File values: ", fileArray, fileValues);
cout << endl << endl;
//sort the file array
sort(fileArray, fileValues);
//print the sorted file array
print("Sorted file values: ", fileArray, fileValues);
return 0;
}
/*
Function: randDouble
Use: Generates a random double value between 1.0 and 250.0
Arguments: This takes no arguments
Returns: a double value that is a random number
*/
double randDouble()
{
//initialize values
double value;
int randNum = rand();
//creates value
value = LOWER_BOUND + (randNum / (RAND_MAX / (UPPER_BOUND - LOWER_BOUND)));
return value;
}
/*
Function: buildRandom
Use: Fills an array of doubles with random numbers and values
Arguments: doubley array[] - an array that gets filled with numbers
Returns: The number of values placed in the array
*/
int buildRandom(double array[])
{
//initialize values
int randNum = rand();
int value, counter;
//set counter
counter = 0;
//creates number
value = MIN_VALUE + (randNum % (MAX_VALUE - MIN_VALUE + 1));
//put value into array based on counter number
while(counter < value)
{
array[counter] = randDouble();
counter++;
}
return value;
}
/*
Function: print
Use: displays numeric information inside of an array then skips to
the next line after 12 outputs
Arguments: string title - prints string
double array [] - gets numbers to print
int numValues - gets amount of numbers to print
Returns: Nothing
*/
void print(string title, double array[], int numValues)
{
//initialize value
int counter = 1;
int extraCounter = 0;
//print prompt
cout << title << endl << endl;
//print value of array based on where it is
while(numValues != extraCounter)
{
cout << fixed << setprecision(2) << setw(8) << right << array[extraCounter];
//skips line at 12, resets counter
if(counter == PRINT_MAX_VALUE)
{
cout << endl;
counter = 0;
}
counter++;
extraCounter++;
}
}
/*
Function: sort
Use: Sorts numbers based on an algorithm
Arguments: double array[] - pulls numbers to sort
int numValues - pulls amount of numbers to sort
Returns: Nothing
*/
void sort(double array[], int numValues)
{
//initialize values
int top, ssf, ptr;
int last = numValues;
//finds smallest value and replaces it
for(top = 0; top < last; top++)
{
for(ptr = top, ssf = top; ptr < last; ptr++)
{
if(array[ptr] < array[ssf])
{
ssf = ptr;
}
}
}
}
/*
Function: buildFile
Use: Opens the file and fills the array
Arguments: double fileArray[] - The array that gets filled
Returns: subscript - amount of values inside the array
*/
int buildFile(double fileArray[])
{
//initialize values
int subscript;
double value;
ifstream input;
//sets subscript to 0
subscript = 0;
//opens file
input.open("nums.txt");
if(input.fail())
{
cout << "nums.txt did not open."<< endl;
exit(-1);
}
//priming read
input >> value;
//fills array
while(input)
{
fileArray[subscript] = value;
subscript++;
input >> value;
}
//closes file
input.close();
return subscript;
}
In sort() at the line ssf = ptr; you are just assigning one local variable to another. The array is unaffected. You need to swap the items in the array.
void sort(double array[], int numValues)
{
//initialize values
int top, ssf, ptr;
int last = numValues;
//finds smallest value and replaces it
for(top = 0; top < last; top++)
{
for(ptr = top, ssf = top; ptr < last; ptr++)
{
if(array[ptr] < array[ssf])
{
double temp = array[ptr];
array[ptr] = array[ssf];
array[ssf] = temp;
}
}
}
}

C++ Sorting the “percentage” of two paired integer arrays [duplicate]

This question already has answers here:
C++ Sorting the "percentage" of two paired integer arrays
(3 answers)
Closed 7 years ago.
I have a program with 2 "paired" integer arrays newNumerator[ ], and newDenominator[ ] which both have 9 integers in them. I wrote a function that sorts them in ascending order (lowest percentage or 'ratio' to highest), however it outputs the elements in the same order as they were before, and doesnt sort it at all. Here is the code, and sortData is the function that is (supposed) to sort it.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cmath>
#include <iomanip>
using namespace std;
typedef int arrayType[];
void readData(int numerator[], int denominator[], int size);
void reportData(arrayType, arrayType, int);
void reportOverall(int numerator[], int denominator[], int size);
void cleanData(int* numerator, int* denominator, const int size, int *newNumerator, int *newDenominator, int &newSize);
void reportMin(int newNumerator[], int newDenominator[], int newSize);
void sortData(int newNumerator[], int newDenominator[], int newSize);
void hrule();
int main()
{
const int size = 12;
int numerator[size];
int denominator[size];
int newSize = 12;
int newNumerator[newSize];
int newDenominator[newSize];
cout << fixed << showpoint << setprecision(1);
readData(numerator, denominator, size);
reportData(numerator, denominator, size);
reportOverall(numerator, denominator, size);
hrule();
cleanData(numerator, denominator, size, newNumerator, newDenominator, newSize);
cout << "There are " << newSize << " scores that are not bonuses:\n";
reportData(newNumerator, newDenominator, newSize);
reportMin(newNumerator, newDenominator, newSize);
hrule();
sortData(newNumerator, newDenominator, newSize);
cout << "The scores from highest to lowest are: " << endl;
reportData(newNumerator, newDenominator, newSize);
system("pause");
return 0;
}
void readData(int numerator[], int denominator[], int size)
{
ifstream dataIn;
dataIn.open("data.txt");
if(!dataIn)
{
cout << "File not found\n";
system("pause");
exit(1);
}
int count;
for(count = 0; count < size; count++)
{
dataIn >> numerator[count];
}
for (count = 0; count < size; count++)
{
dataIn >> denominator[count];
}
dataIn.close();
}
void reportData(arrayType numerator, arrayType denominator, int size)
{
int count;
for (count = 0; count < size; count++)
{
if (denominator[count] == 0)
{
cout << "Score " << (count + 1) << " is " << numerator[count] << "/" << denominator[count] << " = " << "Bonus points!\n";
}
else
{
double percent = 100.0 * static_cast<double>(numerator[count]) / denominator[count];
cout << "Score " << (count + 1) << " is " << numerator[count] << "/" << denominator[count] << " = " << (percent) << "%\n";
}
}
}
void reportOverall(int numerator[], int denominator[], int size)
{
int count;
int totalNumerator = 0.0;
int totalDenominator = 0.0;
for (count = 0; count < size; count++)
{
totalNumerator += numerator[count];
}
for (count = 0; count < size; count++)
{
totalDenominator += denominator[count];
}
double overallPercent = 100.0 * static_cast<double>(totalNumerator) / (totalDenominator);
cout << "Total Points Earned (numerators): " << totalNumerator << endl;
cout << "Total Points Possible (denominators): " << totalDenominator << endl;
cout << "Overall Grade: " << overallPercent << "%\n";
}
void cleanData(int* numerator, int* denominator, const int size, int *newNumerator, int *newDenominator, int &newSize)
{
int count;
int count2 = 0;
for(count = 0; count < size; count++)
{
if(denominator[count] != 0)
{
newNumerator[count2] = numerator[count];
newDenominator[count2] = denominator[count];
count2++;
}
else if(denominator[count] == 0)
{
newSize--;
}
}
}
void reportMin(int newNumerator[], int newDenominator[], int newSize)
{
double minimum;
int count;
int location = 0;
double quotient;
for(count = 0; count < newSize; count++)
{
quotient = 100.0 * static_cast<double>(newNumerator[count]) / newDenominator[count];
if (count == 0 || quotient < minimum)
{
minimum = quotient;
location = count;
}
}
cout << "The lowest earned percentage grade is " << newNumerator[location] << "/" << newDenominator[location] << " = " << minimum << "%\n";
}
void sortData(int newNumerator[], int newDenominator[], int newSize)
{
int temp1;
int temp2;
bool swap;
int count = 0;
double percentageLeft = 100.0 * static_cast<double>(newNumerator[count]) / newDenominator[count];
double percentageRight = 100.0 * static_cast<double>(newNumerator[count + 1]) / newDenominator[count + 1];
do
{ swap = false;
for(count = 0; count < (newSize - 1); count++)
{
if(percentageLeft > percentageRight)
{
temp1 = newNumerator[count];
newNumerator[count] = newNumerator[count + 1];
newNumerator[count + 1] = temp1;
temp2 = newDenominator[count];
newDenominator[count] = newDenominator[count + 1];
newDenominator[count + 1] = temp2;
swap = true;
}
}
} while (swap);
}
void hrule()
{
cout << "\n****************************************\n\n";
}
Data file-
72 49 23 5 9 10 6 16 26 54 14 55
75 50 25 0 10 0 0 20 30 55 15 60
You're computing your percentageLeft and percentageRight outside your loop. Those values never change as you are swapping things.
You probably want them as the first line inside your for loop.
Because the first two don't need to be swapped, it thinks none of the elements ever need to be swapped. If the first two DID need to be swapped, your program would run forever, as the if statement if(percentageLeft > percentageRight) would always be true and swap would always be set to true leading to an infinite loop.

C++ program wont compile with expected expression and function not allowed here

#include <iostream>
using namespace std;
const int lab8 = 10;
int labArray[lab8];
void promptUser(int [], int);
void sortArray(int [], int);
void showArray(const int[], int);
int searchArray(const int [], int, int value);
int x = 0;
int results = 0;
int main()
{
promptUser(labArray, lab8);
sortArray(labArray, lab8);
showArray(labArray, lab8);
cout << "Choose an integer you want to search from the array: " << endl;
cin >> x;
results = searchArray(labArray, lab8, x);
if (results == -1) {
cout << "That number does not exist in the array. \n";
else
{
cout << "The integer you searched for was for at element " << results;
cout << " in the array. \n";
}
}
void promptUser(int numbers[], int size)
{
int index;
for (index = 0; index <= size - 1;index++ )
{
cout << "Please enter ten numbers to fill the array " << endl
<< (index + 1) << ": ";
cin >> numbers[index];
}
}
void sortArray(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);
}
void showArray(const int array[], int size)
{
for (int count = 0; count < size; count++)
{
cout << "The array you entered when sorted was: ";
cout << array[count] << " ";
cout << endl;
}
}
int searchArray(const int array[], int size, int value)
{
int first = 0,
last = size - 1,
middle,
position = - 1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (array[middle] == value)
{
found = true;
position = middle;
}
else if (array[middle] > value)
last = middle - 1;
else
first = middle + 1;
}
return position;
}
I am new to c++ and just working on an assignment for my class. I thought the program I wrote would have worked but for the life of me I can not figure out why it will not compile. I am sure I am missing something or not understanding how it should work completely. The errors I keep receiving are expected expression on line 26 by the 'else' statement and when I put the 'if' and 'else' statements in I started receiving function not allowed here errors. Any help would be greatly appreciated.
In the if statement, you open the bracket { but you never close it. Not sure if this is the problem but it should raise some issues.
if (results == -1) {
cout << "That number does not exist in the array. \n";
**}**
else
{
cout << "The integer you searched for was for at element " << results;
cout << " in the array. \n";
}
This is how it should look. Try it

Sorting through array of pointers

When I try to display the test scores in the function sortArray, I can only access the memory address. How to I access the values of the scores?? Also is the sortArray function correct overall?
#include <iostream>
using namespace std;
void sortArray(int *[], int);
int main()
{
int *testScores = nullptr;
//dynamically allocate an array
int scoreNUMS;
int score;
cout << "Please enter the total number of test scores" << endl;
cin >> scoreNUMS;
testScores = new int[scoreNUMS];
//dynamically allocates an array large enough to hold scoreNUMS
for(int i = 1; i <= scoreNUMS; i++)
{
cout << "Enter student " << i << "'s test score" << endl;
cin >> score;
if (score <= -1)
{
cout << "Please enter positive numbers only!" << endl;
}
*(testScores + i) = score;
//puts the input score in the array
}
sortArray(&testScores, scoreNUMS);
return 0;
}
Im not sure if the function below is correct because I was unaware where to place the * and the &
void sortArray(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);
for(int i = 0; i < size; i++)
cout << *(array + 1) << endl;
}
Error: Array consist scoreNUMS elements, the first one is testScores[0] - first index is zero. And last index is scoreNUMS-1
You must write
for(int i = 0; i < scoreNUMS; i++)
PS: You can use next prototype:
void sortArray(int [], int);
UPD: passing an array to a function is performed by passing a pointer to the first element of the array. (Your array does not copied when you pass it to function)
And run function by this way: sortArray(testScores, scoreNUMS);