I have to read all the data(integers) from file into the array and then iterate the array to make minimum heap and adding them after the last element of the current heap. After reading into array I have to call SiftUp()
on each element which means to move the int into the correct position in the array. Also, I have to count the integers as I read them and set the global heapSize to that.
At the end of all the inputs I am trying to print out the first five elements of the min heap array. output is wrong. My code is not making any minimum heap and thats why output is random. What is wrong with the logic?
input file has 97 integers:
347
765
654
44
15
567
098
//and so on
output:
Please enter the name of the file to open :data.txt
at index 1 :284
at index 2 :870
at index 3 :319
at index 4 :47
at index 5 :312
at index 1 :284 // i dont know why it started again
at index 2 :870
at index 3 :319
at index 4 :47
at index 5 :312 //stops here
my program:
using namespace std;
int heapSize;
void SiftUp(int arr[], int heapSize);
const int arr_Size=100;
int heapArr[arr_Size];
void minHeap(int heapArr[]);
int main()
{
int integers;
string fileName;
ifstream infile;
cout << "Please enter the name of the file to open :";
cin >> fileName;
infile.open(fileName.c_str());
if(!infile)
{
cerr << "An eror occurred while openieng the file.";
exit(1);
}
while(!infile.eof())
{
for (int i=0; i<arr_Size; i++){
infile >> integers;
heapArr[i]=integers;
heapSize=i;
}
}
infile.close();
minHeap(heapArr);
for (int count =1 ; count <=5 ; count ++)
{
cout << " Min at index " << count <<" :"<< heapArr[count] << endl;
}
return 0;
}
void SiftUp(int arr[], int heapSize)
{
int p;
if (heapSize==1) return;
else p = heapSize/2;
if (arr[p] > arr[heapSize]) return;
else swap (arr[heapSize],arr[p]);
SiftUp(arr, p);
}
void minHeap(int arr[])
{
for (int i=0; i <arr_Size ; i++){
SiftUp(arr, heapSize);
}
}
Why are you using arrays to pass as parameters that are already globally defined. I have tried to fix up your code. Have look and do it as it is. Hope, it will work.
int main()
{
int integer;
string fileName;
ifstream infile;
cout << "Please enter the name of the file to open :";
cin >> fileName; // asks user to input filename
infile.open(fileName.c_str()); // opens file
if(!infile)
{
cerr << "An eror occurred while openieng the file.";
exit(1);
}
int i;
for (i=1; i<arr_Size; i++){
infile >> integer;
if(infile.fail())break;
heapArr[i]=integer;
SiftUp(i);
}
infile.close();
heapSize=i;
for (int count =1 ; count <=5 ; count ++)
{
cout << count <<" :"<< heapArr[count] << endl;
}
return 0;
}
void SiftUp(int heapSize){
int p;
if (heapSize==1) return;
p = heapSize/2;
if (heapArr[p] < heapArr[heapSize]) return;
swap (heapArr[heapSize],heapArr[p]);
SiftUp(p);
}