Partition of Array by Element given X - c++

I Am Trying To Find Partition Of Array ,On Condition By Checking Variable x ,when less then x they will be on one side or else on another. but my code need some correction.
HERE am not able to find the error , i will be thankful to you if you help me.
Code is:-
#include<iostream>
using namespace std;
int partition(int arr[],int n,int x){
for(int i=0;i<n;){
if(arr[i]<x){
i++;
}
else if(arr[i]==x){
int temp=arr[i];
arr[i]=arr[n];
arr[n]=temp;
i--;
}
else if(arr[i]>x){
int temp=arr[i];
for(int j=i;j<n;j++){
arr[j]=arr[j+1];
}
arr[n]=temp;
i--;
}
}
return 0;
}
int main(){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
int x;
cin>>x;
partition(arr,n,x);
for(int i=0;i<n;i++){
cout<<arr[i]<<"\t";
}
return 0;
}
Input >> array={2,10,15,1,3,15} ,x=10
Expected << {2,1,3,10,15,15}
Output I get << nothing .

The code isn't giving any output because, first, the "cin" and "cout" are in upper case which is syntactically incorrect, secondly, the variable j is in different case in loop statement and body inside the second else-if clause in the partition function, same goes for the "I" in the first for loop in the main() function. Sort this out and you should be good to go.

First in C++ the size of an array must be a compile-time constant. So for example, consider the following examples:
int n = 10;
int arr[n]; //INCORRECT
The correct way to write the above would be:
const int n = 10;
int arr[n]; //CORRECT
Similarly, in your code,
int n;
cin>>n;
int arr[n]; //INCORRECT because n is not a constant expression
Second, in your code, when you wrote:
arr[n] = temp; Undefined behavior
you're going out of bounds and so you have undefined behavior.
Solution
You can use std::stable_partition and std::vector to solve your problem as shown below:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
int n;
std::cout <<"Enter n:"<<std::endl;
std::cin >> n;
std::vector<int> arr(n); //create a vector of size n instead of an array
std::cout<<"Enter elements: "<<std::endl;
//iterate and take input from user
for(int &elem: arr){
std::cin >> elem ;
}
int x;
std::cout << "Enter x: "<<std::endl;
std::cin>>x;
//use std::partition
std::stable_partition(arr.begin(), arr.end(), [x](int i){return (i < x);});
std::cout<<"This is the partitioned vector: "<<std::endl;
for(int i=0;i<n;i++)
{
std::cout<<arr[i]<<"\t";
}
return 0;
}
Output
The output of the above program is as follows:
Enter n:
6
Enter elements:
2
10
15
1
3
15
Enter x:
10
This is the partitioned vector:
2 1 3 10 15 15
which can be seen here.

Related

Counting elements in an array greater than next element C++

Why is it giving wrong count
In this question we have to find out how many elements are greater than the next element of an array
#include
using namespace std;
int main() {
//number of testcases
int t;
cin>>t;
while(t--){
//taking number of elements in an array
int n,count;
cin>>n;
//taking array
int a[n];
count=0;
for(int i=1;i<=n;i++){
cin>>a[n];
}
//checking array
for(int j=1;j<=n-1;j++){
if(a[j]>a[j+1])
{
count++;
}
}
cout<<count<<endl;
}
return 0;
}
Input
5
1 2 3 4 1
Expected Output
1
Output through above code
2
There are several problems with your code:
Problem 1
You're going out of bounds of the array a which leads to undefined behavior, when you wrote
cin >> a[n]; //undefined behavior
Note that indexing of arrays starts from 0 instead of 1 in C++.
Problem 2
In standard C++, the size of an array must be a compile-time constant. This mean the following is incorrect in your code:
int n;
cin>>n;
int a[n]; //NOT STANDARD C++ BECAUSE n IS NOT A CONSTANT EXPRESSION
Better would be to use std::vector instead of built in array.
int n = 0;
std::cin >> n;
std::vector<int> a(n); //this creates a vector of size n
//take input from user
for(int& element: a)
{
std::cin >> element;
}
int count = 0;
for(int i = 0; i< n - 1; ++i)
{
if(a[i] > a[i+1])
{
++count;
}
}

The output of this question is correct but i am getting a segmentation error

I am trying to solve the program of array rotation. I am getting segmentation error in the code. Can someone please tell where is the problem in this code?
this is the question
Given an unsorted array arr[] of size N, rotate it by D elements (clockwise).
The first line of the input contains T denoting the number of testcases. First line of each test case contains two space separated elements, N denoting the size of the array and an integer D denoting the number size of the rotation. Subsequent line will be the N space separated array elements.
and i have solved it with the following code.
#include <iostream>
using namespace std;
int* rotate(int ar[],int n, int m)
{static int temp[100];
for(int i =0;i<m;i++)
{
temp[i]=ar[i];
}
for(int j =m;j<n;j++)
{
ar[j-m]=ar[j];
}
int x=0;
for(int k =n-m;k<n;k++)
{
ar[k]=temp[x];
x++;
}
return ar;
}
int main() {
//code
int t, n , m;
cin>>t;
while(t>0)
{
cin>>n>>m;
int arr[n];
int * ptr;
for(int i = 0 ;i<n;i++)
{
cin>>arr[i];
}
ptr=rotate(arr,n,m);
for(int j=0;j<n;j++)
cout<<ptr[j]<<" ";
cout<<endl;
t--;
}
return 0;
}
If m > n then it crashes in the first for() loop in rotate as you index past the end of arr.
If m < 0 it crashes in the 2nd loop as it index before arr.
There are probably more cases.

Why am I getting the wrong output for this C++ code? (one of the problem of hackerrank)

This is the program for printing out sum of array elements. It is showing run time error. The output is coming out to be 0 instead of printing out the sum of the elements.
#include<iostream.h>
using namespace std;
void simpleArraySum()
{
int ar[100],n,i,sum=0;
for(i=0;i<n;i++)
{
sum=sum + ar[i];
}
cout<<sum;
}
int main()
{
int ar[100],n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>ar[i];
}
simpleArraySum();
return 0;
}
On this line in your main:
int ar[100], n;
You create an array of 100 elements. You later fill that array using cin
for(int i = 0 ; i < n ; i++)
{
cin >> ar[i];
}
Then you do nothing with that array. You are not calculating any sum. You let that array go, forgotten.
Then, you call a simpleArraySum function. That function is creating an entirely new, distinct array.
// v-----v------There
int ar[100],n,i,sum=0;
That array has no value assigned to it. In fact, reading from it is undefined behavior.
What you want is to receive that array in the arguments of your function:
void simpleArraySum(int* ar, int n) {
// ...
}
And call it like that in your main:
simpleArraySum(ar, 100);
You can avoid the issues of arrays and functions by not using them:
int main()
{
int quantity = 0;
std::cin >> quantity;
int sum = 0;
int value;
while (std::cin >> value)
{
sum += value;
}
std::cout << sum << "\n";
return EXIT_SUCCESS;
}
In simpleArraySum, the variable n is uninitialized. So this loop:
for(i=0;i<n;i++)
invokes undefined behavior when reading from n.
Also, you are summing a different array in the function, than the one you read in mian. It seems that you need to pass in the array from main to this function:
void simpleArraySum(int *ar, int n) {
and call it like this:
simpleArraySum(ar, n);
Finally, you don't even need a function for this, since there is an existing algorithm std::accumulate that you can use:
cout << std::accumulate(ar, ar + n, 0);
In the function, you're adding the elements of ar which is local to the function simpleArraySum() and is not of the array ar that is local to main().
So, pass the array and its length to the function and return its sum. Here is your corrected code:
#include<iostream>
using namespace std;
void simpleArraySum(int ar[], int n)
{
int i, sum = 0;
for(i=0;i<n;i++)
{
sum=sum + ar[i];
}
cout<<sum;
}
int main()
{
int ar[100],n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>ar[i];
}
simpleArraySum(ar, n);
return 0;
}

Bubble sort method for array with dynamically determined size

I am trying to use bubble sort method for array with dynamically determined size. Here's the code:
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter n";
cin>>n;
int arr[n],swap;
cout<<"Enter number"<<endl;
cin>>arr[n];
for(int i=0;i<n-1;i++)
for(int j=0;i<n-i-1;j++)
if(arr[j]>arr[j+1])
{
swap=arr[j];
arr[j]=arr[j+1];
arr[j+1]=swap;
}
for(int k=0;k<n;k++)
cout<<"arr["<<k<<"]="<<arr[k]<<endl;
return 0;
}
When I define the elements of the array in this way the program works:
const n=5;
int arr[n]={1,2,3,4,5)
But I need to enter the size of the array (n) and its elements from the keyboard. But when I run my code the program crashes after I enter the first number. Is there a way to fix it?
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n, swap, temp;
vector<int> arr;
cout<<"Enter n";
cin>>n;
// Loop and accept the n values.
// You may need to take care of the new line.
for(int i = 0; i < n; ++i)
{
cout << "Enter a number : ";
cin >> temp;
arr.push_back(temp);
}
for(int i=0;i<n-1;i++)
for(int j=0;j<n-i-1;j++)
if(arr[j]>arr[j+1])
{
swap=arr[j];
arr[j]=arr[j+1];
arr[j+1]=swap;
}
for(int k=0;k<n;k++)
cout<<"arr["<<k<<"]="<<arr[k]<<endl;
return 0;
}
Notice how a loop is used to extract n values from user. Also using a std::vector relieves you from writing code for a runtime sized array with new and delete.
Also, you inner loop was checking i<n-i-1 and incrementing j which should be j<n-i-1 instead, otherwise j will increment indefinitely till INT_MAX.
The key word is dynamic allocation. In C, the function is malloc. In Cpp, it can be new and delete. Although a vector can work well, it is just a kind of method by STL. Notice that my code may have safe problem.
#include <iostream>
using namespace std;
int main()
{
int n,temp;
cout<<"Enter n:";
cin>>n;
//dynamic allocation
int *arr=new int[n];
cout<<"Enter number."<<endl;
for(int i=0;i<n;i++){
cin>>arr[i];
}
//bubble sort
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
if(arr[i]>arr[j]){
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
//output the array
for(int i=0;i<n;i++){
cout<<"arr["<<i<<"]="<<arr[i]<<endl;
}
delete [] arr;
return 0;
}
You can't take an integer array like that, you need to run a loop. You can take a string like that. There are lot of errors in the bubble sort logic as well, try the below code snippet. It should work fine. You need to dynamically allocate the array for arr
int n,r,swap,i,*arr;
cout<<"Enter n\n";
cin>>n;
arr = (int *)malloc((n)*sizeof(int));
cout<<"Enter numbers\n"<<n<<endl;
for(i=0;i<n;i++)
{
cin>>arr[i];
}
for(i=0;i<n;i++)
{
for(int j=0;j<n-1;j++)//You're checking for i. you need to check for j
{
if(arr[j+1]<arr[j])
{
swap=arr[j];
arr[j]=arr[j+1];
arr[j+1]=swap;
}
}
}
//now print your arr
Includes : #include<stdlib.h>
As mentioned in my comment, you CANNOT dynamically declare the size of arrays in C++ (use std::vector if you are willing to achieve that).
You can then do this:
....
cin >> n;
vector<int> arr(n); // reserves space for `n` integers in the memory
....

CodeChef Problems: Minimum Maximum

I can't seem to understand why this code isn't yielding the correct answer on CodeChef. When I run it on my machine. Seems to yield the correct cost
Problem Link: https://www.codechef.com/problems/MNMX
using namespace std;
int main()
{
unsigned int T, N, cost,element,del;
std::cout<<"Enter the Test Cases";
std::cin>>T;
for (unsigned int i=0;i<T;i++){
std::cout<<"Enter the size of the array";
std::cin>>N;
std::cout<<"Enter the values for "<<i+1<<" Test Case"<<endl;
vector<int> first;
std::cout<<"enter the values of the array"<<endl;
for (unsigned int i=0;i<N;i++){
std::cin>>element;
first.push_back(element);
}
if (N>1){
for (unsigned int i=0;i<N;i++){
element = 0;
element = min (first.front() , first[1]);
del = max (first.front() , first[1]);
first.erase(std::remove(first.begin(), first.end(), del), first.end());
first.push_back(element);
}
}
cost = first.front();
std::cout<<"Cost: "<<cost<<endl;
}
return 0;
}
Generally this kind of test cases will not allow your logs to be part of this so please remove all cout statement except last, which you can modify like
std::cout << cost << std::endl;
Try this on codechef.
Or just edit last main output line as above.
Try using different iterator variables in your for-loops, e.g. j and k for the inner loops.