Forming Heap Using array - c++

I am trying to form a heap using the following code ,But not sure why its not showing the correct output.
#include <iostream>
using namespace std;
int h[10], n;
void heapbottom()
{
int i, j;
for (i = n / 2; i >= 1; i--) {
int k = i;
int v = h[k];
bool heap = false;
while (!heap && 2 * k <= n) {
cout << "\n i value is :" << i;
j = 2 * k;
if (j < n) //there sre 2 children
{
if (h[j] < h[j + 1])
j++;
}
if (v >= h[j])
heap = true;
else {
h[k] = h[j];
k = j;
}
h[k] = v;
} //end of while
}
cout << "\n HEAP GENERATED \n";
for (int i = 0; i < n; i++)
cout << "\n ELEMENT IS:" << h[i];
}
int main()
{
cout << "\n Enter the maximum number of array elements \n";
cin >> n;
cout << "\n Enter the array to perform heap sort \n";
for (int i = 0; i < n; i++)
cin >> h[i];
heapbottom();
return 0;
}

If I change the outer loop to be
for (i = n / 2; i >= 0; i--)
I get 9 8 7 6 5 2 as a result, which I believe is a valid heap.

Related

program which print a matrix in spiral way. ( is not working fine)

I need to write a program which displays the elements of a matrix in a spiral way.My program does not work fine.Here's the code:
#include <iostream>
using namespace std;
void citireMatrice(int a[100][100], int n) // function to read a matrix
{
int i, j;
for (i = 0; i < n; ++i)
{
for (j = 0; j < n; ++j)
{
cout<<"a[" << i << "][" << j << "]=";
cin >> a[i][j];
}
}
}
void spiral(int a[100][100], int n)
{
int i, j, k;
if (n % 2==0)
{
k = n / 2;
}
else
{
k = n / 2 + 1;
}
for (i = 1; i <= k; ++i)
{
for (j = 1; j <= n - i + 1; ++j)
{
cout << a[i][j] << " ";
}
for (j = i + 1; j <= n - i + 1; ++j)
{
cout << a[j][n - i + 1] << " ";
}
for (j = n-i; j >= i; j--)
{
cout << a[n - i + 1][j] << " ";
}
for (j = n-1;j>=i+1;j--)
{
cout << a[j][i];
}
}
}
int main()
{
int a[100][100];
int n;
cout << "n=";
cin >> n;
citireMatrice(a, n);
spiral(a, n);
return 0;
}
If I enter n=2 with the elements 1, 2, 3, 4 it displays 4 -858993460 and other numbers like this.Where's my mistake?
You're properly using zero based indexing of arrays in citireMatrice but in spiral you're using one based indexing.
You need to start your loops at 0, and end at < n. (Consider what element of a will be first to be printed out.)

How do I put any value X after all the minimums in an array?

If I enter an array , at first the code finds the minimums then I want to put zeroes after all the minimums . For example
given an array = 1,1,3,1,1
As we see 1s are the minimum so the result should be = 1,0,1,0,3,1,0,1,0
CODE
#include <pch.h>
#include <iostream>
int main()
{
int min = 10000;
int n;
std::cout << "Enter the number of elements (n): "; //no of elements in the
std::cin >> n; //array
int *array = new int[2 * n];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> array[i];
if (array[i] > min)
min = array[i];
}
for (int i = 0; i < n; i++) {
if (array[i] == min) { // Not very clear about this
for (int k = n; k > i; k--) // part of the code, my teacher
array[k] = array[k - 1]; //explained it to me , but i
array[i + 1] = 0; // didn't understand (from the
i++; // `for loop k` to be precise)
n++;
}
std::cout << array[i] << ", 0";
}
return 0;
}
But my answer doen't put zeroes exactly after minimums
There are few issues in your code, first of all your min is wrong. I have fixed your code with comments on fixes I have made. Please take a look :
#include "stdafx.h"
#include <iostream>
int main()
{
int min = 10000;
bool found = 0;
int n;
std::cout << "Enter the number of elements (n): "; //no of elements in the
std::cin >> n; //array
int *array = new int[2 * n];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> array[i];
if (array[i] < min) //< instead of >
min = array[i];
}
for (int i = 0; i < n; i++) {
if (array[i] == min)
{
for (int k = n; k > i; k--)
{
array[k] = array[k - 1];
}
array[i + 1] = 0;
i++; //increment i here because you don't want to consider 0 that you have just added above.
n++; //since total number of elements in the array has increased by one (because of 0 that we added), we need to increment n
}
}
//print the array separately
for (int i = 0; i < n; i++)
{
std::cout << array[i];
if (i != n - 1)
{
std::cout << ",";
}
}
return 0;
}
The first issue was in the calculation of min: < instead of >.
Another problem if that you are modifyng the paramers iand ninside the loop. This is rather dangerous and implies to be very cautious.
Another issue was that it should be i++; n++; instead of i--,n--;
Here is the code:
// #include <pch.h>
#include <iostream>
int main()
{
int min = 1000000;
int n;
std::cout << "Enter the number of elements (n): "; //no of elements in the
std::cin >> n; //array
int *array = new int[2 * n];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> array[i];
if (array[i] < min)
min = array[i];
}
for (int i = 0; i < n; i++) {
if (array[i] == min) { // Not very clear about this
for (int k = n; k > i; k--) // part of the code, my teacher
array[k] = array[k - 1]; //explained it to me , but i
array[i + 1] = 0; // didn't understand (from the)
i++;
n++;
}
}
for (int i = 0; i < n; i++) {
std::cout << array[i] << " ";
}
std::cout << "\n";
return 0;
}

Counting number of copying and comparisons in heapsort and insertation sort

I want to count how many times does algorithm makes comparisons and how many times algorithm makes copying.
#include <stdio.h>
#include <random>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <time.h>
void generuoti(int _N, const char *_file);
void nuskaityti(const char *_file);
int ps = 0;
int ks = 0;
void heapify(double arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
ps+=1;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
ps += 1;
// If largest is not root
if (largest != i)
{
std::swap(arr[i], arr[largest]);
ps += 1;
ks += 1;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
// pagr funkcija haep sortui
void heapSort(double arr[], int n)
{
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--)
{
// Move current root to end
std::swap(arr[0], arr[i]);
ks+=1;
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
void insertion_sort(double arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
ks+=1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
ks+=1;
ps+=1;
}
arr[j + 1] = key;
ks+=1;
}
}
using namespace std;
double *Data;
double* A;
double* B;
double N;
int main()
{
srand(time(NULL));
cout << "Generuojame atsitktinius duomenis" << endl;
generuoti(20000, "duom.txt");
cout << "Nuskaitome duomenis" << endl;
nuskaityti("duom.txt");
A = new double[(int)N];
B = new double[(int)N];//jeigu algoritmui reikia papildomo masyvo
for (int i = 0; i < N; i++) {
A[i] = Data[i];
}
cout << "Pradine skaiciu seka:" << endl;
for (int i = 0; i < N; i++)
cout << A[i] << " ";
cout << endl;
//
insertion_sort(A, N);
//heapSort(A, N);
//truksta veiksmu sk
cout << "Surusiuota skaiciu seka:" << endl;
for (int i = 0; i < N; i++)
cout << A[i] << " ";
cout << endl;
cout << "Kopijavimu skaicius " << ks << endl;
cout << "Palyginimu skaicius " << ps << endl;
system("pause");
return 0;
}
void generuoti(int _n, const char *_file) {
ofstream os(_file);
os << _n << endl;
for (int i = 0; i<_n; i++)
os << " " << 500+ (double)(rand() % 3001) ;
os.close();
}
void nuskaityti(const char *_file) {
ifstream is(_file);
if (is.fail()) {
cout << "Failo nera" << endl;
exit(1);
}
is >> N;
Data = new double[(int)N];
for (int i = 0; i < N; i++) {
is >> Data[i];
}
}
This is my code, and ps - is equal to a number of comparisons, and ks - is equal to number of copying. I want to ask if I counted all comparisons and all copying in the algorithms? Thanks for answers.
No
if (l < n && arr[l] > arr[largest])
largest = l;
ps+=1;
There are two problems here. Assuming you are talking about double comparisons (rather than integer), the comparison may or may not occur.
Secondly your indentation is deeply misleading. (You always increment.)
You need
if (l < n) {
ps++; // About to compare
if (arr[l] > arr[largest])
largest = l;
}
There are probably other errors, but it is impossible to tell because I can't read your language, so the printed text, comments, and names are meaningless.
Given you are writing in C++, I would write a class with operator <() and operator =, and a copy constructor, and instrument those. That way you cannot possibly get it wrong.

Finding all saddle points in a matrix c++

I'm working on a code that finds all saddle points in a matrix. Both smallest in their row and biggest in their column, and biggest in their row and smallest in their column fall under the definition (of my university) of a saddle point. Being a beginner I managed to get half of it done (finding saddle points which are smallest in their row and biggest in their column) by copying parts of what we've done in class and typing it myself. I have been stuck on it for quite some time and can't figure how to add the saddle points which are biggest in their row and smallest in their column to the program.
This is what I have so far:
#include <iostream>
#include <cstdlib>
using namespace std;
int a[10][10];
int x, y;
int pos_max(int j) //saddle points check
{
int max = 0;
for (int i = 1; i <= x - 1; i++) {
if (a[i][j] > a[max][j]) {
max = i;
}
}
return max;
}
int main() {
cout << "Enter the number of rows: ";
cin >> x;
cout << "Enter the number of columns: ";
cin >> y;
cout << "----------------------------" << endl;
for (int i = 0; i <= x - 1; i++) //input of the matrix
for (int j = 0; j <= y - 1; j++) {
cout << "a[" << i + 1 << ", " << j + 1 << "] = ";
cin >> a[i][j];
}
cout << "----------------------------\n";
for (int i = 0; i <= x - 1; i++) //visualization of the matrix
{
for (int j = 0; j <= y - 1; j++)
cout << a[i][j] << " ";
cout << endl;
}
cout << "----------------------------\n";
int r;
int flag = 0;
int i = y;
for (int j = 0; j <= y - 1; j++) {
r = pos_max(j);
for (i = 0; i <= y - 1; i++) {
if (a[r][i] < a[r][j]) {
break;
}
}
if (i == y) {
cout << "Saddle points are: ";
cout << "a[" << r + 1 << ", " << j + 1 << "] = " << a[r][j] << "\n";
flag = 1;
}
}
if (flag == 0) {
cout << "No saddle points\n";
}
cout << "----------------------------\n";
return 0;
}
First, there is a logical error with your code. In the pos_max function, it will return the index of the element which is maximum in the column. There can be a case when there are multiple maximum with the same value in the column, however, it returns the one which is not the minimum in the row, hence your program won't be able to print that saddle point.
To solve this, you can either return an array of all indices which are maximum in a column and then check for each of those points if it's minimum in their respective column, but I think it's not a very elegant solution. In any case, you will again have to write the entire code for the other condition for saddle points, minimum in column and maximum in row.
Hence, I would suggest a change in strategy. You create 4 arrays, max_row, max_col, min_row, min_col, where each array stores the minimum / maximum in that row / column respectively. Then you can traverse the array and check if that point satisfies saddle point condition.
Here is the code:
#include <iostream>
#include <cstdlib>
using namespace std;
int a[10][10];
int max_row[10], max_col[10], min_row[10], min_col[10];
int x, y;
bool is_saddle(int i, int j) {
int x = a[i][j];
return (max_row[i] == x && min_col[j] == x) || (min_row[i] == x && max_col[j] == x);
}
int main() {
/* code to input x, y and the matrix
...
*/
/* code to visualize the matrix
...
*/
/* populating max and min arrays */
for (int i = 0; i <= x-1; ++i) {
max_row[i] = a[i][0], min_row[i] = a[i][0];
for (int j = 0; j <= y-1; ++j) {
max_row[i] = max(max_row[i], a[i][j]);
min_row[i] = min(min_row[i], a[i][j]);
}
}
for (int j = 0; j <= y-1; ++j) {
max_col[j] = a[0][j], min_col[j] = a[0][j];
for (int i = 0; i <= x-1; ++i) {
max_col[j] = max(max_col[j], a[i][j]);
min_col[j] = min(min_col[j], a[i][j]);
}
}
/* Check for saddle point */
for (int i = 0; i <= x-1; ++i) {
for (int j = 0; j <= y-1; ++j) {
if (is_saddle(i, j)) {
cout << "Saddle points are: ";
cout << "a[" << i + 1 << ", " << j + 1 << "] = " << a[i][j] << "\n";
flag = 1;
}
}
}
if (flag == 0) {
cout << "No saddle points\n";
}
cout << "----------------------------\n";
return 0;
}
#include <iostream>
using namespace std;
int getMaxInRow(int[][5], int, int, int);
int getMinInColumn(int[][5], int, int, int);
void getSaddlePointCordinates(int [][5],int ,int );
void getInputOf2dArray(int a[][5], int, int);
int main()
{
int a[5][5] ;
int rows, columns;
cin >> rows >> columns;
getInputOf2dArray(a, 5, 5);
getSaddlePointCordinates(a,rows,columns);
}
void getInputOf2dArray(int a[][5], int rows, int columns)
{
for (int i = 0; i < rows; i = i + 1)
{
for (int j = 0; j < columns; j = j + 1)
{
cin >> a[i][j];
}
}
}
void getSaddlePointCordinates(int a[][5],int rows,int columns)
{
int flag = 0;
for (int rowNo = 0; rowNo < 5; rowNo++)
{
for (int columnNo = 0; columnNo < 5; columnNo++)
{
if (getMaxInRow(a, rows, columns, rowNo) == getMinInColumn(a, rows, columns, columnNo))
{
flag = 1;
cout << rowNo << columnNo;
}
}
}
if (flag == 0)
cout << "no saddle point";
cout << "\n";
}
int getMaxInRow(int a[][5], int row, int column, int rowNo)
{
int max = a[rowNo][0];
for (int i = 1; i < column; i = i + 1)
{
if (a[rowNo][i] > max)
max = a[rowNo][i];
}
return max;
}
int getMinInColumn(int a[][5], int row, int column, int columnNo)
{
int min = a[0][columnNo];
for (int i = 1; i < row; i = i + 1)
{
if (a[i][columnNo] < min)
min = a[i][columnNo];
}
return min;
}
just take the reference arr(ref[size]) // memorization method to check the minimum and maximum value in it.
Here is the Code Implementation with time complexity O(n *n) & space complexity O(n):
#include <bits/stdc++.h>
using namespace std;
#define size 5
void util(int arr[size][size], int *count)
{
int ref[size]; // array to hold all the max values of row's.
for(int r = 0; r < size; r++)
{
int max_row_val = arr[r][0];
for(int c = 1; c < size; c++)
{
if(max_row_val < arr[r][c])
max_row_val = arr[r][c];
}
ref[r] = max_row_val;
}
for(int c = 0; c < size; c++)
{
int min_col_val = arr[0][c];
for(int r = 1; r < size; r++) // min_val of the column
{
if(min_col_val > arr[r][c])
min_col_val = arr[r][c];
}
for(int r = 0; r < size; r++) // now search if the min_val of col and the ref[r] is same and the position is same, if both matches then print.
{
if(min_col_val == ref[r] && min_col_val == arr[r][c])
{
*count += 1;
if((*count) == 1)
cout << "The cordinate's are: \n";
cout << "(" << r << "," << c << ")" << endl;
}
}
}
}
// Driver function
int main()
{
int arr[size][size];
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size; j++)
cin >> arr[i][j];
}
int count = 0;
util(arr, &count);
if(!count)
cout << "No saddle points" << endl;
}
// Test case -> Saddle Point
/*
Input1:
1 2 3 4 5
6 7 8 9 10
1 2 3 4 5
6 7 8 9 10
0 2 3 4 5
Output1:
The cordinate's are:
(0,4)
(2,4)
(4,4)
Input2:
1 2 3 4 5
6 7 8 9 1
10 11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Output2:
No saddle points
*/

How do i add all the values in my ascending array?

First i need to re-arrange all the values of my array into ascending order then add it afterwards. For example the user input 9 2 6, it will display in ascending order first ( 2 6 9 ) before it will add the sum 2 8 17.. The problem is my ascending order is not working, is there something wrong in my code?
#include <iostream>
#include<conio.h>
using namespace std;
int numberof_array, value[10], temp;
int i = 0, j;
void input()
{
cout << "Enter number of array:";
cin >> numberof_array;
for (i = 0; i < numberof_array; i++)
{
cout << "Enter value for array [" << i + 1 << "] - ";
cin >> value[i];
cout << endl;
}
}
void computation()
{
// this is where i'll put all the computation
for (j = 0; j < numberof_array; j++)
{
cout << value[j];
}
for (i = 0; i <= numberof_array; i++)
{
for (j = 0; j <= numberof_array - i; j++)
{
if (value[j] > value[j + 1])
{
temp = value[j];
value[j] = value[j + 1];
value[j + 1] = temp;
}
}
}
}
void display()
{
// display all the computation i've got
cout << "\nData after sorting: ";
for (j = 0; j < numberof_array; j++)
{
cout << value[j];
}
getch();
}
int main()
{
input();
computation();
display();
}
void computation(){
for (int j = 0; j < numberof_array; j++) cout << value[j]<<"\t";
for (int i = 0; i <= numberof_array; i++) {
temp = value[i];
int temp_idx = i;
for (int j = i; j < numberof_array; j++) {
if (value[j] < temp) {
temp = value[j];
temp_idx = j;
}
}
int temp_swap = value[i];
value[i] = value[temp_idx];
value[temp_idx] = temp_swap;
}
}
How about changing your second function to something like above.
I have to agree with other commentators that your coding style is not preferred but there might be more to the story than meets the eye.