Heapsort using Priority queue C++ - c++

My code works for putting data into the array but when I print it out, it always crashes after first number. There must be something wrong with my bubbledown function, could you point out what is wrong with it? Thank you in advance.
#include<iostream>
#include <string>
#include<fstream>
using namespace std;
void bubbleup(int pq[], int back);
void bubbledown(int pq[], int front, int back);
void swap(int &a, int &b);
int main(){
ifstream infile;
ofstream outfile;
string input, output;
int size,number;
int front=1, back=0;
int *pq=new int[size]; // dynamically allocate array
cout<<"What's the input file name?"<<endl;
getline(cin, input); // get the input name
infile.open(input.c_str());// open the input file
while(!(infile.eof())){
infile>>number; // infile to an integer type variable first instead of an array. this is why your program doesn't work!!!!!
back++;
pq[back]=number;
bubbleup(pq,back);
for(int i=1;i<=back;i++)
cout<<pq[i]<<" ";
cout<<endl;
}
cout<<"what's the output file name?"<<endl;
getline(cin, output);
outfile.open(output.c_str());
while(back!=0){
cout<< pq[front]<<endl;
outfile<< pq[front]<<endl;
pq[front]=pq[back];
back--;
bubbledown(pq,front,back);
}
}
//bubbleup function
void bubbleup(int pq[], int back)
{
int fatherindex=back/2;
while(!(pq[back]>=pq[fatherindex])||!(back==1)){
if(pq[back]<pq[fatherindex])
swap(pq[back],pq[fatherindex]);
back=fatherindex;
fatherindex=back/2;
}
}
//bubbledown function
void bubbledown(int pq[], int front, int back){
int fatherindex=front,kidindex;
while(2*fatherindex+1 <= back){
kidindex=2*fatherindex+1;
if((kidindex+1<back) && (pq[kidindex]<pq[kidindex+1])){
kidindex++;
}
if(pq[fatherindex] > pq[kidindex]){
swap(pq[fatherindex],pq[kidindex]);
fatherindex=kidindex;
}
else
return;
}
}
//swap function
void swap(int &a, int &b){
int t=a;
a=b;
b=t;
}

A few problems to look at
You don't initialize size before using it, so your pq memory could be any size at all.
You are using 1-based access to your arrays, so make sure you allocate one more than you need.
while(!back==0) will work, but it is doing boolean logic on an int, then comparing the result with an int. while(back!=0) is a lot easier to read and will produce fewer compiler warnings.
Edit: also your bubbleDown function has an infinite loop when neither if test is triggered.

Related

Count the occurence of a particular digit in a range of number

I was trying to count the number of digit 2 in an range of number (say 2-22, the answer would be 6: 2,12,20,21,22 as 22 contribute twice). This is the code that I came up with, yet it fails to run after value input. Any ideas?
#include <iostream>
#include <cstdio>
using namespace std;
int main(){
int lowerbound,upperbound,sum=0;
int nofNum(int num);
scanf("%d %d",&lowerbound,&upperbound);
for (int i=lowerbound;i<=upperbound;++i){
sum+=nofNum(i);
}
printf("%d",sum);
return 0;
}
int nofNum(int num){
int count=0;
while(num!=0){
if (num%10==2){
count++;
num/=10;
}
}
return count;
}
you are using c not c++. Your mistake is that nofNum wasn't declared before you used it. It has to be declared before the line you use it.
int nofNum(int num);
would declare it.
You will still need to implement it, which you allready did.
alternatively you can move the implementation st. it is above main, where you used it.
EDIT: i just saw you declared it inside main, which is uncommon at best. you really should not do that.
EDIT2:
you messed up that if statement in numOf
int nofNum(int num){
int count=0;
while(num!=0){
if (num%10==2){
count++;
}
num/=10; // may not be inside if, since num would not be adjusted
// if the last digit isnt a 2
}
return count;
}
EDIT3:
you can use input and output streams in c++ to replace scanf and printf:
scanf("%d %d",&lowerbound,&upperbound);
becomes
std::cin >> lowerbound >> upperbound;
and
printf("%d",sum);
becomes
std::cout << sum << std::endl;
Edit4:
suggested form:
// declarations - this is what would belong to the *.h file later on.
int nofNum(int num);
followed by
int nofNum(int num) { /*implementation*/ }
int main(int /*argc*/, char* /*argv*/[]) { /*implementation*/ }
or
// this is valid because we allready heard of nofNum through declaration
int main(int /*argc*/, char* /*argv*/[]) { /*implementation*/ }
int nofNum(int num) { /*implementation*/ }
the upper form doesn't require the declarations because each function allready is implemented before you use them, therefore the compiler allready knows what nofNum is supposed to be.

I have written a code to find reverse of array elements but it doesnot gives required output

# include <iostream>
using namespace std;
const int size=5;
void inputdata(int arr[], int n); //function prototype
void display(int arr[],int n); //function prototype
void Reverse(int arr[],int n); //function prototype
int main() //start of main function
{
int list[size]; //array declaration
inputdata(list ,size); //fuction call
display(list,size); //fuction call
Reverse(list,size); //fuction call
}
void inputdata(int arr[], int n) //function definition that takes input from user
{
int index;
for(index=0;index<n;index++) //loop to take input from user
{
cout<<"Enter element ["<<index<<"]"<<endl;
cin>>arr[index];
}
}
void display(int arr[],int n) //displays the input
{
int index;
for(index=0;index<n;index++) //loop to display output
{
cout<<"Element on ["<<index<<"] is:"<<arr[index]<<endl;
}
}
void Reverse(int arr[],int n) //function to find reverse
{
int i,temp; //here i have taken a variable temp of integer type for swapping
for(i=0;i<n/2;i++)
{
temp=arr[i];
arr[i]=arr[n-i-1];
arr[n-i-1]=arr[i];
}
cout<<"the reverse order array is:"<<endl;
for(i=0;i<n;i++) //this loop is used to display the reverse order
{
cout<<arr[i]<<endl;
}
return 0;
}
this above c++ code is meant to find the reverse of the elements of array which is taken as input from user.Input data function is used to take input from the user.Display function is used to display that input.Then there is a function reverse which finds the reverse.
But it does not gives proper reverse(output) e.g if i enter 5 array elements as 1,2,3,4,5 its output should be as 5,4,3,2,1.But this results as 5,4,3,4,5.
Your swap code looks like:
temp=arr[i];
arr[i]=arr[n-i-1];
arr[n-i-1]=arr[i];
But it should be:
temp=arr[i];
arr[i]=arr[n-i-1];
arr[n-i-1]=temp;
A cleaner and simpler option would be to use the swap function in the algorithm library.

C++ Arrays and Vectors

I am new to C++ and this is not really part of my major so I am a little lost! If I can contact anyone personally for help please let me know :)
My program will need to read in ten integer values from a file, and store them in an array or vector. The reading of the values should be done in a separate function that takes an integer array as a parameter, and read from a file named tempInput.txt. I am unsure how to create an integer array as a parameter.
Then, from main, you will call another function, whose signature and return type is thus:
bool isDangerous(int tempArray[ ]);
If you could help me with part one or two that would be great!
namespace std;
int divison(int,int);
int main()
{
void readData(int tempArray[ ]);
int tempInput[10];
readData(tempInput);
//int size=10; //Array size
int sum =0;
//for(int i=0;i<size;i++) //Loop which inputs arrays data and
// {
//cout << myArray[i] << endl;
// }
return 0;
}
As best as I can understand the question, here's some code to get you started (Note that I haven't filled in everything exactly, I don't want to do your work for you)
#include<fstream> //So we can read from files
#include<iostream>
using namespace std;
void readData(int tempArray []) {
//Open file and read data into temp array
//If you need help reading data, see:
//http://www.cplusplus.com/doc/tutorial/files/
}
bool isDangerous(int tempArray []) {
//Do things
}
int main() {
int tempInput [10];
readData(tempInput); //Read the data into tempInput
bool result;
result = isDangerous(tempInput); //Do something with isDangerous
return 0;
}

Passing array as parameter in C++ ERROR

I tried to "select sort" an array. But instead of displaying the original array with just a "for loop", to go beyond the normal way and implement the stuffs I learned I decided to pass the original array to a function called "org_array" and tried to invoke it in the "void main()". But got couple of errors. I can't figure out what's the error I made in passing the parameters. Help please?
Code:
#include<iostream>
#include<conio.h>
using namespace std;
extern int s;
void org_array(int arr[30],int y);
void main()
{
int i,n,j,pos,a[30];
cout<<"Enter n: "<<endl;
cin>>n;
cout<<"\nEnter array: "<<endl;
for(i=0;i<n;i++){
cin>>a[i];
}
cout<<"Orginal Array: ";
org_array(a[30],n);
/*for(i=0;i<n;i++){
cout<<a[i]<<" | ";
}*/
for(i=0;i<n-1;i++)
{
int small=a[i];
pos=i;
for(j=i+1;j<n;j++)
{
if(a[j]<small)
{
small=a[j];
pos=j;
}
}
int temp=a[i];
a[i]=a[pos];
a[pos]=temp;
}
cout<<"\tSorted Array: ";
for(i=0;i<n;i++){
cout<<a[i]<<" | ";
}
getch();
}
void org_array(int arr[30],int y){
for(s=0;s<y;s++)
{
cout<<" "<<arr[s];
}
}
org_array(a[30],n);
is incorrect. It should be:
org_array(a,n);
And main should return int as per ISO. Further your declarations and definitions respectively should be this way:
void org_array(int [],int); // declaration - removed 30 since we might want to pass an array of larger size
void org_array(int arr[],int y) //definition
{
for(int s=0;s<y;s++) // You did not declare s as int
{
cout<<" "<<arr[s];
}
}
Just a side note:
An lvalue [see question 2.5] of type array-of-T which appears in an expression decays (with three exceptions) into a pointer to its first element; the type of the resultant pointer is pointer-to-T because an array is not a "modifiable lvalue,"
(The exceptions are when the array is the operand of a sizeof or & operator, or is a literal string initializer for a character array.)
In your code:
cout<<"Orginal Array: ";
org_array(a[30],n);
Should pass just the name of array as argument. Arrays are passed as reference to address of block of memory. You are referring to a specific index in array in your call. http://www.cplusplus.com/doc/tutorial/arrays/
org_array(a,n);
In your code:
void org_array(int arr[30],int y){
for(s=0;s<y;s++)
{
cout<<" "<<arr[s];
}
}
for loop requires a type for variable s. I assume you want an integer.
for(int s=0; s<y; s++)
Your main function should also be of type int and return int value.

Binary Search with few modification

While I am trying to compile the code with few modification in binary search recursive function. The program is acting weird. Some time it gives the correct value and some time it goes to infinite loop. Please explain what went wrong with the code. I am using DEV C++ as an IDE.
CODE:
#include<iostream>
#include<sstream>
using namespace std;
//function to compare the two integers
int compare(int low, int high)
{
if (low==high)
return 0;
if (low<high)
return 1;
else
return -1;
}
//Function for binary search using recursion
int *BinarySearch(int *Arr,int Val,int start,int end)
{
int localstart=start;
int localend=end;
int mid=(start+end)/3;
cout<<"MID:"<<mid;
int comp= compare(Val,Arr[mid]);
if(comp==0)
return &(Arr[mid]);
else if (comp>0)
return BinarySearch(Arr,Val,localstart,mid-1);
else
return BinarySearch(Arr,Val,mid+1,localend);
return NULL;
}
main()
{
int *arr;
arr= new int [256];
string str;
getline(cin,str);
stringstream ss;
ss<<str;
int index=0;
while(ss>>arr[index])
{index++;}
//cout<<arr[index-1];
cout<<"Enter Value:";
int value;
cin>>value;
int *final;
final=BinarySearch(arr,value,0,index-1);
if(final!=NULL)
cout<<"Final:"<<*final;
else
cout<<"Not Found";
getchar();
getchar();
return 0;
}
Two ideas:
What should BinarySearch do if Val is not in the array? Trace out what your code does in this case.
(start+end)/3 probably isn't the middle of the current range.