Printing a binary tree whose elements are stored in a array - c++

I want to print a complete binary tree with n elements where 1<=n<=m & m is a natural number and these elements are stored in an array.
My approach :
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int a=0;a<n;a++)cin>>arr[a];
/*Printing the sorted tree*/
int l=1,cnt=1;
while(l<=n)
{
cnt++;
l=l+pow(2,cnt);
}
int val=0,cn=1,loli;
while(1)
{
for(int p=cnt;p>=1;p--) cout<<" ";
for(int ll=1,loli=1;ll<=pow(2,val);ll++){
if(cn==n)return 0;
if(loli!=2){
cout<<arr[cn++]<<" ";
loli++;
}
else{
cout<<arr[cn++];
loli=1;
}
}
val++;
cnt=cnt-2;
if(cnt==0)cnt=1;
cout<<endl;
}
return 0;
}
I found some related answers there . But the discussion is using link list may be (nodes) where I do not want to use nodes for taking elements of tree. I am taking them from an array.

It's difficult to follow your code because:
It's not clear how you're approaching this problem
You don't break into functions (which you should)
You use cryptic names for variables
You have a strange dependence on an entirely artificial parameter, m. Why do we care about m at all?
If you follow better practices solving this problem - starting with describing your algorithm clearly (to yourself if to no-one else) - you will probably get it right.

Related

Modulo strength , want explanation in the algorithm used to compute the answer

I was trying to solve the problem Modulo strength at hackerearth ,
https://www.hackerearth.com/practice/basic-programming/implementation/basics-of-implementation/practice-problems/golf/modulo-strength-4/ , so basically we have to find all such pairs of no. (say i,j) such that A[i]%k=A[j]%k where k is a no. given in the question , i tried brute force approach and got time limit exceeded at some of the last test cases and in the discussion tab i found a code which is working but i couldn't understand what exactly it does, and the underlying thinking behind the algorithm used.
#include <bits/stdc++.h>
using namespace std;
#define int long long
int32_t main() {
int n,k,s=0;
cin>>n>>k;
int a[n];
vector<int>v(k,0); // Specially this part ,what does it store?
for(int i=0;i<n;i++)
{
cin>>a[i];
v[a[i]%k]++;
}
for(int i=0;i<k;i++)
{
s+=v[i]*(v[i]-1);
}
cout<<s;
}
Here is the code, i wanted to understand it so that i can apply this logic over other problems.
There are a few problems with that;
"bits/stdc++.h" is not a standard header
Variable-length arrays, like int a[n], are non-standard and prone to runtime errors (this one is also completely unnecessary)
#define int long long makes the code have undefined behaviour.
Here is a fixed version, with some minor renaming and clarifying comments:
#include <iostream>
#include <vector>
int main() {
long long n, k;
cin >> n >> k;
// There are k groups of friends.
std::vector<int> friends(k);
// Count how many people there are in each group.
for(int i = 0; i < n; i++)
{
int x;
std::cin >> x;
friends[x%k]++;
}
long long sum = 0;
for(int i = 0; i < k; i++)
{
// In a group of N mutual friends, each person has N-1 friends.
sum += friends[i] * (friends[i]-1);
}
std::cout << sum;
}
Let's first go through with the purpose of every variable in the code.
The purpose of n,k,s is explicitly given.
a[n] is for reading the numbers in array.
std::vector<int>v(k,0) stores k sized vector of 0's, and v[i] indicates the number of variables in a[n] for which a[j]%k==i.
In the last loop, the following has done. The number of pairs that can be constructed with n elements is n*(n-1) (basic combinatorics), and if we have v[i] numbers for which the condition is satisfied and a[j]%k==i the number of pairs that can be constructed is v[i]*(v[i]-1). The loop sums up the number of pairs for every remnant i.

Vscode Complies the sorting algorithms but does not give any output. These are running fine in an online compiler.[I have MinGW installed]

/*Bubble sort*/
#include <iostream>
using namespace std;
//function to sort the array
int bubble_sort (int k[], int n){
int t,ct=1;
while(ct<n){
for(int i=0;i<n-ct;i++){
if(k[i]>=k[i+1]){
t=k[i];
k[i]=k[i+1];
k[i+1]=t;
}
ct++;
}
}
///loop to o/p the sorted array
for(int i=0;i<n;i++){
cout<<k[i]<<" ";
}cout<<endl;
return 0;
}
int main(){
int l;
int r[l];
cout<<"Enter the array size"<<endl;
cin>>l;
cout<<"Enter elements"<<endl;
for(int i=0;i<l;i++){
cin>>r[i];
}
bubble_sort(r,l);
return 0;
}
/*Insertion Sort*/
#include <iostream>
using namespace std;
//function to sort the array
int insertion_sort (int k[], int n){
int t,ct=1;
for(int i=1;i<n;i++){
int current=k[i];
int j=i-1;
while(k[j]>current && j>=0){
k[j+1]=k[j];
j--;
}
k[j+1]=current;
}
for(int i=0;i<n;i++){
cout<<k[i]<<" ";
}cout<<endl;
return 0;
}
int main(){
int l;
int r[l];
cout<<"Enter the array size"<<endl;
cin>>l;
cout<<"Enter elements"<<endl;
for(int i=0;i<l;i++){
cin>>r[i];
}
insertion_sort(r,l);
return 0;
}
The images attached show the output that I get in the terminal(which is blank) when I run the respective codes. The first algorithm illustrates the bubble sorting algorithm and the 2nd is meant to implement insertion sorting technique.
Any help in this regard is much appreciated!
Output in the terminal for bubble sort code
Output in the terminal for the insertion sort code
This part of your main contains typical C++ newbie errors.
int l;
int r[l];
cout<<"Enter the array size"<<endl;
cin>>l;
When you write int l, you only reserve some memory and give a nice name l to it. The value of l is arbitrary, or rubbish. Then you write int r[l]. This has several problems in it. First, the C++ language does not allow for such array definitions unless l is a constant whose value is known to the compiler. So this is an error, but many compilers do not flag it as an error, because they magically allow this particular departure from the standard and call it "extension" (VLA). The price for it is that your program is not standard and its behavior may be compiler-dependent. Second, as you already know, the value of l is undefined. Thus, any execution of your program may result in a different output, including correct (expected) behavior or even a sudden death (crash).
What yoo ned to do is this:
declare a variable that will store the array size. Give to it a meaningful name, like size, avoid names like l, as they are sometimes difficult to tell from 1 and I.
read its value from std::cin
construct an array of size size. Do not use the int a[size] syntax, for you already know it is not permitted by the standard. Use std::vector.
If after these changes your program still behaves in a strange way, call for help again.
Also, before you ask for help again, please include these flags to gcc:
-Wall -pedantic
They will issue lots of diagnostic information if your program does not adhere to usual coding standards (-Wall) or the C++ standard (-pedantic). Work on your source code until you can see no errors and no warnings.

I am working on finding the min value in a random array, and anyone know that why my code is not working? C++

Here's what I did.
I am working on find the min value in a random array,
Anyone know that why my code is not working?
It output with lowest valus : 0 and located on a complex number
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int x,min,n;
int array[1000];
for(int i=1;i<=1000;i++)
{
x = rand()% 1000 + 1;
array[i] = x;
}
min=array[0];
for(int i=0;i<1000;i++)
{
if(array[i]<min)
{
min=array[i];
n=i;
}
}
cout<<"The Lowest Value : "<<min<<"\nIts located at { "<< n <<" }"<<endl;
cout<<" "<<endl;
return 0;
}
Get used to always initialising your variables. In this case you use n before it is written first time.
int x=1,min=1001,n=0;
Also heed the hint by seccpur (alternatively mine) from comments.
Here is mine again, for making a complete answer:
Get used to for(int i=0;i<arraysize;i++) in C++. Otherwise you will always trip over the 0-indexing.
for(int i=0;i<1000;i++)
Both problems together cause your problem of outputting the weird index (from non-initialised n) and the implausible value 0 (from non-initialised array[0]).
With your way of random numbers, 0 is impossible, but if it happens to be in index 0, then it will be the lowest of all and never be replaced by anything meangingful.
You got "lucky" (actually I consider it unlucky not being told about this kind of error...) with accessing beyond the array...

how to iterate an array only up to where it is filled without traversing to full length

I like to fill this array to only up to a[4] and want to traverse only up to 4th position not the enire length.
int main()
{
int a[10],i,j=0;
cout<<"\nEnter 4 number :";
for(i=0;i<4;i++)
{
cin>>a[i];
}
while(a[j]!='\0')
{
cout<<a[j];
j++;
}
}
this code prints 11 numbers
If you can use a special value, such as zero, to indicate the items past the end, the way '\0' is used in C strings, you could use your approach after initializing a to all zeros:
int a[10] = {0};
...
while (a[j]) {
cout << a[j++];
}
The downside to this approach is that the end-marker becomes invalid in the input. In other words, if end-user enters a zero among the four inputs, printing will stop after printing fewer than four items.
That is why these two approaches are more common:
Use a dynamic container, such as std::vector<int> - this approach is valid only in C++
Store the number of items in a separate variable - if you must use a "raw" array, this approach is the most common.
The answer is: You can't. int arrays have nothing like a C style string termination.
An array has a fixed size and the array can't tell how many elements that you have written to. So if you want to use an array for this, you'll have to ad code to count how many elements that you have written, i.e. by using an extra variable for counting.
Like:
int a[10],i,j=0;
int valid_elements = 0;
cout<<"\nEnter 4 number :";
for(i=0;i<4;i++)
{
cin>>a[i];
++valid_elements;
}
for(i=0;i<valid_elements;i++)
{
cout<<a[i];
}
However, that is normally not a good approach.
A much better approach is a vector as the number of elements in a vector is dynamic. You can do something like:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> a;
int i, j;
cout<<"\nEnter 4 number :";
for(i=0;i<4;i++)
{
cin>>j;
a.push_back(j);
}
for (int x : a) // Range based for loop automatic iterates all elements in the vector
{
cout<<x;
}
return 0;
}

Determining the number of shifts performed in insertion sort?

I am trying to solve this question http://www.mycodeschool.com/work-outs/sorting/7
The question is to find no of shifts in Insertion Sort.
I have written the code but couldn't figure out where I am going wrong in logic
http://ideone.com/GGjZjw
#include<iostream>
#include<cstdio>
#include<cmath>
// Include headers as needed
using namespace std;
int main()
{
// Write your code here
int T,count,n,*a;
// int imin;
cin >> T;
int value,hole;
while(T--)
{
cin >> n;
count=0;
a=new int[n];
//reading the input array
for(int i=0;i<n;i++)
{
cin >> a[i];
}
// considering the 0th element to be already sorted and
// remaining list unsorted
for(int i=1;i<n;i++)
{
value=a[i];
hole=i;
// shifting
while(hole>0&&a[hole-1]>value)
{
//
a[hole]=a[hole-1];
hole=hole-1;
count++;
}
a[hole]=value;
}
// cout << count<<endl;
}
// Return 0 to indicate normal termination
return 0;
}
The number of swaps made in insertion sort is equal to the number of inversions in the array (the number of pairs of elements that are out of order). There is a well-known divide-and-conquer algorithm for counting the number of inversions in an array that runs in time O(n log n). It's based on a slightly modified version of mergesort, and I think you shouldn't have too much trouble coding it up.
The problem with your approach is that you're not correctly implementing insertion sort, what you've achieved is an inverse bubble-sort.
for a slightly less complex (yet with worse complexity :P) than #templatetypedef 's O(n log n) solution you can solve it in the same complexity of the sort O(n^2) by applying the correct implementation.
you should implement a function for swap(int* array, int index_a, int index_b) than count how many times this function was called.
this Link to wikipedia has a good pseudo-code for you