Bubble sort issue - c++

Currently studying software engineering at college (first year) and made a program where the user enters how many entries there will be and then they input the times for each entry and it is sorted in descending order.
The problem I am having is when I enter a large number for the first input it doesn't sort correctly but the rest do. It would be great if someone could help me out with this and sorry for the noob question:P
The entire code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int TotalSize = 0;
void getSpeed(int *CalculationTime, int NoOfCalculations)
{
for (int i = 0; i < NoOfCalculations; i++)
{
cout << "Please enter the speed of calculation " << i + 1 << "(Ms): "; cin >> CalculationTime[i];
}
}
void sort_speeds(int *CalculationTime, int NoOfCalculations)
{
// Sorting speeds in decending order
bool swapped = true;
int i, j = 0;
int temp;
while (swapped)
{
swapped = false;
j++;
for (i = 1; i < NoOfCalculations - j; i++)
{
if (CalculationTime[i] > CalculationTime[i + 1])
{
temp = CalculationTime[i];
CalculationTime[i] = CalculationTime[i + 1];
CalculationTime[i + 1] = temp;
swapped = true;
}
}
}
// Output times decending order
for (int i = 0; i < NoOfCalculations; i++)
{
cout << CalculationTime[i] << "\n";
}
}
int main()
{
// Declaring & Initializing variables
int NoOfCalculations = 0;
int *CalculationTime = new int[NoOfCalculations];
// Getting user input
cout << "How many calculations are there? "; cin >> NoOfCalculations;
getSpeed(CalculationTime, NoOfCalculations);
// Sorting and displaying times
sort_speeds(CalculationTime, NoOfCalculations);
system("pause");
return 0;
}

You've never compare first element of your array with anything - for (i = 1; i < NoOfCalculations - j; i++) should be for (i = 0; i < NoOfCalculations - j; i++)

The issue is for (i = 1; i < NoOfCalculations - j; i++) You are starting at position 1, start at position 0 and it fixes the problem. for (i = 0; i < NoOfCalculations - j; i++)

// Declaring & Initializing variables
int NoOfCalculations = 0;
int *CalculationTime = new int[NoOfCalculations];
// Getting user input
cout << "How many calculations are there? "; cin >> NoOfCalculations;
Bzzzt. You allocate a zero-element array, and then don't reallocate it. I bet if you entered a large enough number for your number of calculations, your program would crash.
Really, you want to be using std::vector, an extremely useful datastructure, the use of which is a bit outside of the scope of this answer. Basically, you can do stuff like this:
std::vector<int> getSpeeds(int NoOfCalculations)
{
std::vector<int> speeds;
for (int i = 0; i < NoOfCalculations; i++)
{
int speed;
std::cout << "Please enter the speed of calculation " << i + 1 << "(Ms): ";
std::cin >> speed;
speeds.push_back(speed);
}
return speeds;
}
You can use the returned vector almost exactly as if it were an array:
std::vector<int> speeds = getSpeeds(10);;
if (CalculationTime[3] > CalculationTime[4])
// do something
Often, in a C++ application, the explicit use of pointers is a sign that you're not using the standard library, and as a result making life much, much harder for yourself.
Oh, and also:
for (i = 1; i < NoOfCalculations - j; i++)
You never look at NoOfCalculations[0] or NoOfCalculations[i - 1], so you never touch the first element.

while (swapped)
{
swapped = false;
j++;
for (i = 0; i < NoOfCalculations - j; i++) //try and start i from 0. I think you are missing the first element to check
{
if (CalculationTime[i] > CalculationTime[i + 1])
{
temp = CalculationTime[i];
CalculationTime[i] = CalculationTime[i + 1];
CalculationTime[i + 1] = temp;
swapped = true;
}
}
}

Related

Sum of two arrays, carry over operation C++

Beginner here, and I'm stuck. The main program is provided to us, and we're supposed to write 3 functions. readBig(), addBig(), and printBig(). I'm stuck on the addBig() function. It's supposed to sum two arrays, and perform the carry operation. I cannot figure out where I'm going wrong. The carry operation is working out for me.
Any help/direction is appreciated.
#include <iostream>
using namespace std;
//This program will test three functions capable of reading, adding,
//and printing 100-digit numbers.
// Do not change these function prototypes:
void readBig(int[]);
void printBig(int[]);
void addBig(int[], int[], int[]);
// This constant should be 100 when the program is finished.
const int MAX_DIGITS = 100;
//There should be no changes made to the main program when you turn it
in.
int main(){
// Declare the three numbers, the first, second and the sum:
int num1[MAX_DIGITS], num2[MAX_DIGITS], sum[MAX_DIGITS];
bool done = false;
char response;
while (not done)
{
cout << "Please enter a number up to "<<MAX_DIGITS<< " digits: ";
readBig(num1);
cout << "Please enter a number up to "<<MAX_DIGITS<< " digits: ";
readBig(num2);
addBig(num1, num2, sum);
printBig(num1);
cout << "\n+\n";
printBig(num2);
cout << "\n=\n";
printBig(sum);
cout << "\n";
cout <<"test again?";
cin>>response;
cin.ignore(900,'\n');
done = toupper(response)!='Y';
}
return 0;
}
//ReadBig will read a number as a string,
//It then converts each element of the string to an integer and stores
it in an integer array.
//Finally, it reverses the elements of the array so that the ones digit
is in element zero,
//the tens digit is in element 1, the hundreds digit is in element 2,
etc.
void readBig(int num[])
{
for(int i = 0; i < MAX_DIGITS; i++){
num[i] = 0;
}
string numStr;
getline(cin,numStr);
string temp;
//store into array
for (int i = 0; i < numStr.length(); i++){
temp = numStr.at(i);
num[i] = stoi(temp);
}
int arrayLength = MAX_DIGITS;
int temp2;
for (int i = 0; i < (arrayLength/2); i++){
temp2 = num[i];
num[i] = num[(arrayLength - 1) - i];
num[(arrayLength - 1) - i] = temp2;
}
}
//AddBig adds the corresponding digits of the first two arrays and
stores the answer in the third.
//In a second loop, it performs the carry operation.
void addBig(int num1[], int num2[], int sum[])
{
for (int i = 0; i < MAX_DIGITS; i++){
sum[i] = num1[i] + num2[i];
if (sum[i] > 9){
sum[i] = sum[i] - 10;
sum[i+1] = sum[i+1] + 10;
}
}
}
//PrintBig uses a while loop to skip leading zeros and then uses a for
loop to print the number.
void printBig(int array[])
{
int i = 0;
while (array[i] == 0){
i++;
}
for (int j = i; j < MAX_DIGITS;j++){
cout << array[j] << endl;
}
}
Looks like readBig function isn't correct, it stores least significiant digit into num[numStr.length()-1], after reversing it became num[MAX_DIGITS -1 - ( numStr.length()-1], but addNum assumes last digit is num[0].
Correct variant:
void readBig(int num[])
{
//clear num, read numStr...
//store into array
int count = 0;
for (int i = numStr.length()-1; i >= 0; --i){
temp = numStr.at(i);
num[count++] = stoi(temp);
}
|
So this
sum[i] = sum[i] - 10;
sum[i+1] = sum[i+1] + 10;
should most likely be this
sum[i] = sum[i] - 10;
sum[i+1] = sum[i+1] + 1;
Since its the next decimal place it shouldnt be incremented by 10
Also when you get to the last cell in your array
sum[i+1] = sum[i+1] + 1;
this will be out of bounds, so depending on the requirments you will want to change this

display wheter or not an array entered by the user is unique or not

I am new to C++ I am making an array based off of user input and displaying whether the array is unique or not. my initial thought is I have to end up creating another array to store values and then compare the elements. My code compiles without errors but does not do what I want it to do. I can't used advanced methods such as hashmaps or vectors. Any help or insight is greatly appreciated!
#include <iostream>
#include <string>
using namespace std;
int main()
{
int myArray[6];
string name;
int i, k;
int ov = 0;
int newVal = 0;
for (int index = 0; index < 6; index++)
{
cout << "Enter number a number: ";
cin >> myArray[index];
}//end loop for
for (i = 0; i < 6; i++)
{
ov = myArray[i];
}
for (k = i + 1; k < 6; k++)
{
if (ov == myArray[k])
{
newVal = 1;
}
}
if (newVal == 1)
{
cout << "Not all unique";
}
else
{
cout << "All unique";
}
cin.get();
return 0;
}

Visual c++ 2010 vector positioning doesn't seem to update

I've got this small piece of code
int row[7];
bool equals = false;
std::vector<int>range;
for(int i = 1; i <= 35; ++i)
{
range.push_back(i);
}
for(int i = 0; i < 7; i++){
int number = range[rand() % range.size() + 1];
std::vector<int>::iterator pos = find(range.begin(), range.end(), number);
row[i] = number;
range.erase(range.begin() + (*pos - 1));
std::cout << row[i] << endl;
}
return 0;
It takes away random elements from the vector, the problem I've got is that every time I remove a object from the vector the size updates but the positions doesn't seem to change on the individual numbers in the vector, making the program crash since I sometimes travel outside the bounds of the vector.
I've tried with vector::shrink_to_fit but it didn't seem to re-evaluate the vectors item positions.
What am I missing? It seems like such a simple thing to do but I just can't wrap my head around it.
P.S
I'm a c++ scrub so if you have any input on the code being bad/unsafe I'm open for suggestions/constructive criticism.
rand() % range.size() + 1
can go outside the bounds of the vector
use
rand() % range.size()
use this piece of code instead :
std::vector<int>range;
for(int i = 1; i <= 35; ++i)
{
range.push_back(i);
}
srand(time(0)) ;
for(int i = 0; i < 7; i++){
int index = rand() % range.size() ;
int number = range[index];
row[i] = number;
range.erase(range.begin() + index);
std::cout << row[i] << endl;
}

C++ insertion sort

I have this function called WordSort(worddata W [], int count) that is fed two variables
1 - worddata is the array holding information on a given word in a file. count is just the counter variable to see which word in the array we are looking at.
the words.txt file that is read into this program would just be a string of words.
this is a list of words
there are letters and numbers
23 people recommend this program.
Heres the function:
void WordSort (worddata W [], int count)
{
for (int i=1; i < count; i++)
{
for (int j=i; j > 0 && W[j-1].word > W[j].word; j--)
{
Swap(W[j], W[j-1]);
}
}
}
The swap function is suppose to swap every element with the one before it as long as j > 0 or the list is over. Im confused on how to complete the swap function, here's the example i was given.
void Swap (worddata & a, worddata & b)
{
int += a;
a = b;
b =+;
}
Swap is suppose to swap every element with the one before it
I think the WordSort function works fine, the only thing missing is the Swap function. Could anyone point me in the right direction or explain insertion sorting better to me?
void insertion_sort()
{
/* Algorithm : Insertion Sort
* Coded by .
*/
int num;
/*
* Asking the User no of Integers he/she wants to enter
*/
cout << "Enter no of integers u want to enter: ";
cin >> num;
/* Creating an Array to store the integers*/
int s[num];
/*Taking Integers from the User */
for(int i = 0 ; i < num ; i++)
{
cout << "Integer " << i+1 << " is : ";
int x;
cin >> x;
s[i] = x;
}
/* The Magic of INSERTION SORT */
for(int j = 1 ; j <= (num-1) ; j++)
{
int key = s[j];
int k = j-1;
while(k >=0 && key <= s[k])
{
s[k+1] = s[k];
k = k - 1;
}
s[k+1]=key;
}
/*Printing Out the Sorted List */
cout << "The Sorted List is \n\n";
for(int i = 0 ; i < num ; i++)
{
cout << s[i] << " ";
}
}
Use standard library std::swap instead. In your loop:
for (...)
{
std:swap(W[j], W[j-1]);
}
std::swap requires worddata class to have a copy constructor and an assignment operator defined explicitly or implicitly.
Swap should look like this -- I have no idea how your example is even close.
void Swap (worddata & a, worddata & b)
{
worddata temp = a;
a = b;
b = temp;
}
Insertion sort using "for loop" (2 iterations)
#include<iostream>
using namespace std;
int insertion(int arr[], int size_arr)
{
int i,j,n, temp;
for(i=1;i<size_arr; i++){
j=i-1;
temp = arr[i];
for (j; j >= 0; j--)
{
if(arr[j] > temp){
arr[j+1] = arr[j];
arr[j] = temp;
}
}
arr[j] = temp;
}
for(i=0;i<size_arr;i++){
cout<<arr[i]<<endl;
}
return 0;
}
int main(){
int arr[] = {3,38,1,44,66,23,105,90,4,6};
int size_arr = sizeof(arr) / sizeof(arr[0]);
insertion(arr,size_arr);
return 0;
}

Finding multiples of integers quickly

I've written out this particular code in C++ to try and find out all the multiples of the integers 3 & 5 below 1000 by using a while loop and then storing it in integer arrays. I also want to print each of those multiples out. But every time I debug this program, it endlessly prints out '0'. I just don't understand. Can someone please explain how to correct this code and why that unusual output occurs?
#include <iostream>
using namespace std;
int main()
{
const int three_limit = 334;
const int five_limit = 200;
int threeArray[three_limit] = {0};
int fiveArray[five_limit] = {0};
int i = 1, j = 1;
while (i < three_limit)
{
int multiples = 3*i;
multiples = threeArray[i - 1];
cout << threeArray[i - 1] << endl;
i++;
}
while (j < five_limit)
{
int multiples = 5*i;
multiples = fiveArray[j - 1];
cout << fiveArray[j - 1] << endl;
j++;
}
char response;
cin >> response;
return 0;
}
Your output will have duplicates when the number contains multiples of 3 and 5, e.g. 15, 30.
Some of the suggestions use multiplication or mod (%) which are quite slow, but there's a much faster solution using a binary array that will also help you avoid the duplication problem. Something like:
int main() {
bool nums[1001];
for(int i = 1; i < 1001; ++i)
nums[i] = 0;
for(int i = 3; i < 1001; i += 3)
nums[i] = 1;
for(int i = 5; i < 1001; i += 5)
nums[i] = 1;
for(int i = 1; i < 1001; ++i)
if(nums[i])
cout << i << endl;
}
It should be
threeArray[i - 1] = multiples;
instead of
multiples = threeArray[i - 1];
See the following code, to generate multiples of 5
#include<stdio.h>
int main(){
int max=1000;
int i=1,result=0;
while(result!=max && i!=200)
{
result=5*i; // change the 5 by 3 for multiples of 3
printf("\n %d",result);
i++;
}
}
I guess this
multiples = threeArray[i - 1];
should really be
threeArray[i - 1] = multiples;
Try debugging it again and watch multiples while executing this line.
multiples = threeArray[i - 1];
You're overwriting the local int with the (empty) contents of the array - you have your assignment the wrong way around.
You never modify the values in your array. It should be something like this:
while (i < three_limit)
{
int multiples = 3*i;
threeArray[i-1] = multiples;
cout << threeArray[i - 1] << endl;
i++;
}