So the question is to figure out whether the array is ascending or not ascending meaning that if the array is 2,3,4,6 it would display yes it is ascending, if it is 3,2,5,6 it would display no not ascending.
I'm cant seem to get the program to display a 0 which mean not ascending and I Know the issue is somewhere in the for loop or if statement but I don't know how to fix it
#include <iostream>
using namespace std;
int ascending(int x[], int npts);
int main()
{
int number[10];
int num;
cout<<"How many numbers would you like to enter? (max = 10) ";
cin>>num;
for(int i = 0; i<num; i++)
{
cout<<"Enter number ";
cin>>number[i];
}
int asc = ascending(number, num);
cout<<asc;
}
int ascending(int x[], int n)
{
int count = 0;
for(int i = 0; i<n-1; i++)
{
if(x[i]<x[i + 1])
count++;
if(count <= n - 1)
return 1;
else
return 0;
}
}
Your issue is in the ascending function, you're returning 1 after the first iteration. In order to determine if the sequence of numbers is ascending, you must iterate through all of them. However,if you find a number that's not ascending at any time, then you can return 0 right away. If you safely iterate through all them without returning 0, than you know the sequence is ascending
int ascending(int x[], int n)
{
for(int i = 0; i<n-1; i++)
{
if(x[i]>=x[i + 1])
return 0
}
return 1
}
int ascending(int x[], int n)
{
int i = 0;
Do
{
if(x[i]> x[i + 1])
return 0;
i++;
} while (i < n-1);
return 1;
}
Related
I tried to implement number of inversions in an array, using merge sort.
Every time I execute this code, I get different value of the number of inversions. I am not able to figure out the reason for this. Please have a look at the code and tell me the mistake.
#include<stdio.h>
#include<iostream>
using namespace std;
int count =0;
void merge(int A[],int start,int mid,int end)
{
int size1 = mid-start+1;
int size2 = end-(mid+1)+1;
int P[size1];
int Q[size2];
for(int i=0;i<size1;i++)
P[i]=A[start+i];
for(int j=0;j<size2;j++)
Q[j]=A[mid+j+1];
int k = 0;
int l = 0;
int i =0;
while(k<mid && l<end)
{
if(P[k]>Q[l])
{
A[i] = Q[l];
l++; i++;
count++;
}
else
{
A[i] = P[k];
k++; i++;
}
}
}
void inversions(int A[],int start,int end)
{
if(start!=end)
{
int mid = (start+end)/2;
inversions(A,start,mid);
inversions(A,mid+1,end);
merge(A,start,mid,end);
}
}
int main()
{
int arr[] = {4,3,1,2,7,5,8};
int n = (sizeof(arr) / sizeof(int));
inversions(arr,0,n-1);
cout<<"The number of inversions is:: "<<count<<endl;
return 0;
}
int k = 0;
int l = 0;
int i =0;
while(k<mid && l<end)
{
if(P[k]>Q[l])
{
A[i] = Q[l];
l++; i++;
count++;
}
else
{
A[i] = P[k];
k++; i++;
}
}
Few mistakes here, i starts from start and not 0. k must loop from 0 till size1 and not till mid. Similarly, l must loop from 0 till size2 and not till end. You are incrementing count by 1 when P[k] > Q[l] but this is incorrect. Notice that all the elements in array P following the element P[k] are greater than Q[l]. Hence they also will form an inverted pair. So you should increment count by size1-k.
Also, the merge procedure should not only count the inversions but also merge the two sorted sequences P and Q into A. The first while loop while(k<size1 && l<size2) will break when either k equals size1 or when l equals size2. Therefore you must make sure to copy the rest of the other sequence as it is back into A.
I have made the appropriate changes in merge and pasted it below.
void merge(int A[],int start,int mid,int end)
{
int size1 = mid-start+1;
int size2 = end-(mid+1)+1;
int P[size1];
int Q[size2];
for(int i=0;i<size1;i++)
P[i]=A[start+i];
for(int j=0;j<size2;j++)
Q[j]=A[mid+j+1];
int k = 0;
int l = 0;
int i = start;
while(k<size1 && l<size2)
{
if(P[k]>Q[l])
{
A[i] = Q[l];
l++; i++;
count += size1-k;
}
else
{
A[i] = P[k];
k++; i++;
}
}
while (k < size1)
{
A[i] = P[k];
++i, ++k;
}
while (l < size2)
{
A[i] = Q[l];
++i, ++l;
}
}
int P[size1];
int Q[size2];
VLA (Variable length arrays) are not supported by C++. size1 and size2 are unknown during compile time. So, each time they get a different value and hence the difference in output.
Use std::vector instead
std::vector<int> P(size1, 0); //initialize with size1 size
std::vector<int> Q(size2, 0); //initialize with size2 size
I am trying to use bubble sort to sort a set of random numbers. But my code results in a messed up order. For example, instead of it sorting 9 12 15 100 150,it will sort as 12 15 100 9 150. Any help will be appreciated. Below is my code.
#include <iostream>
#include <cstdlib>
using namespace std;
void sortArray(int[], int);
void showArray(const int[], int);
int main()
{
const int MIN_VALUE = 1;
const int MAX_VALUE = 200;
int numbers[MAX_VALUE];
for (int count = 0; count < MAX_VALUE; count++)
{
numbers[count] = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
cout << numbers[count]<< endl;
sortArray(numbers, count);
showArray(numbers, count);
}
}
void sortArray(int numbers[], int size)
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size -1); count++)
{
if (numbers[count] > numbers[count + 1])
{
temp = numbers[count+1];
numbers[count+1] = numbers[count];
numbers[count] = temp;
swap = true;
}
}
} while (swap);
}
void showArray(const int numbers[], int size)
{
for (int count = 0; count < size; count++)
cout <<numbers[count] << endl;
}
Thanks
The sorting code is correct.
The only problem is that you're calling the sort and printing out the array in the same loop that is filling the data.
You should first fill all the data, then sort, then display the sorted result.
So, I am writing a code which creates an array with an elements and amount of elements written by user and then a code generates a biggest value which last digit is zero. So, I have accomplished a step of writing an array which is elements entered by user. The hardest part( for me) is to complete a code which generates biggest value which last digit is zero. So yeah, I need an advice in completing this code. Thank you.
for example :
An array - 2 20 25 300 55555
The biggest number which last digit is zero is 300
So yeah, I need an advice in completing this code. Here is a code what I have done so far :
#include "stdafx.h"
#include <stdlib.h>
#include <windows.h>
#include <time.h>
int GetAmount() {
int howmany;
printf("Enter amount of elements - ");
scanf_s("%i", &howmany);
return howmany;
}
void GetArray(int a[], int n) {
printf("Enter elements - \n");
for (int i = 0; i < n; i++)
{ printf("%i ->", i);
scanf_s("%i", &a[i]);
}
}
int LastDigitZero(int n[], int a) {
for (int i = 0; i < a; i++)
{
if (n[i] % 10 == 0) {
return 0;
}
}
}
int maxvalue(int a[], int n) {
int temp = 0;
for (int i = 0; i < n; i++)
{
if (a[i] > temp) {
temp = a[i];
}
}
return temp;
}
void main() {
int amount = GetAmount();
int array[100];
GetArray(array, amount);
int max = maxvalue(array, amount);
printf("Max Value is %i\n", max);
}
Thank you for your attention, have a nice day! :)
It works! That's how it looks!
#include "stdafx.h"
#include <stdlib.h>
#include <windows.h>
#include <time.h>
int GetAmount() {
int howmany;
printf("Enter amount of elements - ");
scanf_s("%i", &howmany);
return howmany;
}
void GetArray(int a[], int n) {
printf("Enter elements - \n");
for (int i = 0; i < n; i++)
{ printf("%i ->", i);
scanf_s("%i", &a[i]);
}
}
int maxvalue(int a[], int n) {
int temp = 0;
for (int i = 0; i < n; i++)
{
if (a[i] % 10 == 0 && a[i] > temp) {
temp = a[i];
}
}
return temp;
}
void main() {
int amount = GetAmount();
int array[100];
GetArray(array, amount);
int max = maxvalue(array, amount);
printf("The biggest number which last digit is zero is %i\n ", max);
system("pause");
}
Thank you guys for the answers! That was fast!!! :)
You almost have it. First any number that ends in 0 mod 10 is 0 so that is how you can check if the last digit is 0. With that you would change maxvalue() to
int maxvalue(int a[], int n) {
int temp = a[0];
for (int i = 1; i < n; i++)
{
if (a[i] % 10 == 0 && a[i] > temp) {
temp = a[i];
}
}
return temp;
}
I also made a change to set temp to the value of a[0] as if your array is all negative numbers then 0 would be the largest number. Since temp is already a[0] we can then start the for loop at 1.
You should check if there is a solution, in this example you could check that the value returned by maxValue finishes by 0 (if none of the values finishes by 0 then it would return a[0]):
int maxValue(int a[], int n) {
int temp= a[0]
for (int i(1); i<n;i++) {
if (a[i] % 10 == 0 && (temp % 10 != 0 || a[i] > temp )) temp = a[i];
}
return temp;
}
I created a program to show the sum and show the reversed number a person has typed. The sum function works but the revers function is not. Can anyone give me any tips on how to fix it.
I created a program to show the sum and show the reversed number a person has typed. The sum function works but the revers function is not. Can anyone give me any tips on how to fix it.
#include<iostream>
#include<iomanip>
using namespace std;
void printSum(int n, bool reverse);
int sm(int n);
int reverseInt(int n);
void printAddTable(int n);
int main()
{
int reverse;
int sum=0;
int n;
cout<<"Enter N value:"<<endl;
cin>>n;
if(n>0)
{
reverse = true;
printSum( n, reverse); // calls the printSum Method
}
else
{
//cout<<"enter positive Number only:"<<endl;
}
sum = sm(n); //err // calls the sum Method
reverse = reverseInt(n); // calls the reverseInt Method
cout<<"The reverse value is:"<<reverse;
printAddTable(n); // calls the printAddTable Method
//getch()
}
//end of main()
void printSum(int n, bool reverse)
{
int sum=0;
// print sum of reverse numbers
for(int i=n; i>=1; i--)
{
sum=sum+i;
cout<<i<< " "<<"+"<<" ";
}
cout<<sum;
}
int sm(int n)
{int sum =0;
for(int i=1; i<=n; i++)
{
sum = sum + i ;
cout << endl;
cout<<i<<" "<<"+"<<" "<<endl; // print n positive integers
cout << endl;
}
cout<< "Are " <<n<< " positive integers"<<endl;
cout<< "Sum is "<<sum <<endl;
return sum;
}
int reverseInt(int n)
{
int reminder=0;
int sum =0;
while(n<=0)
{
reminder = n/10;
sum = (sum * 10) + reminder; // it returns the reverse number
n = n % 10;
}
return sum;
}
void printAddTable(int n)
{
for(int i=1; i<=n; i++)
{
cout<<i<<endl;
for(int j=1; j<=n; j++) // print n X n add table
{
cout<<i+j<<endl;
}
}
}
{
In your code, following is to be changed in reverseInt function as mentioned by the comment.
while(n<0)
{
//reminder = n/10; should be
reminder = n%10;
sum = (sum * 10) + reminder; // it returns the reverse number
//n = n % 10;
//Should be
n = n/10; //or n /= 10;
}
Okay, so after struggling with trying to debug this, I have finally given up. I'm a beginner in C++ & Data Structures and I'm trying to implement Heap Sort in C++. The code that follows gives correct output on positive integers, but seems to fail when I try to enter a few negative integers.
Please point out ANY errors/discrepancies in the following code. Also, any other suggestions/criticism pertaining to the subject will be gladly appreciated.
//Heap Sort
#include <iostream.h>
#include <conio.h>
int a[50],n,hs;
void swap(int &x,int &y)
{
int temp=x;
x=y;
y=temp;
}
void heapify(int x)
{
int left=(2*x);
int right=(2*x)+1;
int large;
if((left<=hs)&&(a[left]>a[x]))
{
large=left;
}
else
{
large=x;
}
if((right<=hs)&&(a[right]>a[large]))
{
large=right;
}
if(x!=large)
{
swap(a[x],a[large]);
heapify(large);
}
}
void BuildMaxHeap()
{
for(int i=n/2;i>0;i--)
{
heapify(i);
}
}
void HeapSort()
{
BuildMaxHeap();
hs=n;
for(int i=hs;i>1;i--)
{
swap(a[1],a[i]);
hs--;
heapify(1);
}
}
void main()
{
int i;
clrscr();
cout<<"Enter length:\t";
cin>>n;
cout<<endl<<"Enter elements:\n";
for(i=1;i<=n;i++) //Read Array
{
cin>>a[i];
}
HeapSort();
cout<<endl<<"Sorted elements:\n";
for(i=1;i<=n;i++) //Print Sorted Array
{
cout<<a[i];
if(i!=n)
{
cout<<"\t";
}
}
getch();
}
I've been reading up on Heap Sort but I'm not able to grasp most of the concept, and without that I'm not quite able to fix the logical error(s) above.
You set hs after calling BuildMaxHeap. Switch those two lines.
hs=n;
BuildMaxHeap();
When I implemented my own heapsort, I had to be extra careful about the indices; if you index from 0, children are 2x+1 and 2x+2, when you index from 1, children are 2x and 2x+1. There were a lot of silent problems because of that. Also, every operation needs a single well-written siftDown function, that is vital.
Open up Wikipedia at the Heapsort and Binary heap articles and try to rewrite it more cleanly, following terminology and notation where possible. Here is my implementation as well, perhaps it can help.
Hmmm now that I checked your code better, are you sure your siftDown/heapify function restricts sifting to the current size of the heap?
Edit: Found the problem! You do not initialize hs to n before calling BuildMaxHeap().
I suspect it's because you're 1-basing the array. There's probably a case where you're accidentally 0-basing it but I can't spot it in the code offhand.
Here's an example if it helps.
#include <iostream>
#include <vector>
using namespace std;
void max_heapify(std::vector<int>& arr, int index, int N) {
// get the left and right index
int left_index = 2*index + 1;
int right_index = 2*index + 2;
int largest = 0;
if (left_index < N && arr[left_index] > arr[index]) {
// the value at the left_index is larger than the
// value at the index of the array
largest = left_index;
} else {
largest = index;
}
if (right_index < N && arr[right_index] > arr[largest]) {
// the value at the right_index is larger than the
// value at the index of the array
largest = right_index;
}
// check if largest is still the index, if not swap
if (index != largest) {
// swap the value at index with value at largest
int temp = arr[largest];
arr[largest] = arr[index];
arr[index] = temp;
// once swap is done, do max_heapify on the index
max_heapify(arr, largest, N);
}
}
void build_max_heap(std::vector<int>& arr, int N) {
// select all the non-leaf except the root and max_heapify them
for (int i = N/2 - 1; i >= 0; --i) {
max_heapify(arr, i, N);
}
}
void heap_sort(std::vector<int>& arr) {
int N = arr.size();
int heap_size = N;
// build the max heap
build_max_heap(arr, N);
// once max heap is built,
// to sort swap the value at root and last index
for (int i = N - 1; i > 0; --i) {
// swap the elements
int root = arr[0];
arr[0] = arr[i];
arr[i] = root;
// remove the last node
--heap_size;
// perform max_heapify on updated heap with the index of the root
max_heapify(arr, 0, heap_size);
}
}
int main() {
std::vector<int> data = {5,1,8,3,4,9,10};
// create max heap from the array
heap_sort(data);
for (int i : data) {
cout << i << " ";
}
return 0;
}
# include <iostream> //Desouky//
using namespace std;
void reheapify(int *arr, int n, int i)
{
int parent = i; // initilaize largest as parent/root
int child1 = 2 * i + 1; // to get first chid
int child2 = 2 * i + 2; // to get second child
if (child1 < n && arr[child1] > arr[parent]) // if child2 > parent
{
parent = child1;
}
//if child > the parent
if (child2 < n && arr[child2] > arr[parent])
{
parent = child2;
}
// if the largest not the parent
if (parent != i)
{
swap(arr[i], arr[parent]);
// Recursively heapify the affected sub-tree
reheapify(arr, n, parent);
}
}
void heapsort(int *arr, int n)
{
// build a heap
for (int i = n - 1; i >= 0; i--)
{
reheapify(arr, n, i);
}
// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--)
{
// Move current root to end
swap(arr[0], arr[i]);
// call max heapify on the reduced heap
reheapify(arr, i, 0);
}
}
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int n;
cin >> n;
int* arr = new int[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
heapsort(arr, n);
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
}