I have implemented an algorithm to change an array so that all the even numbers are moved to the beginning of the array and the old numbers to the end of the array. Here is my program :-
#include <iostream>
using namespace std;
void print(int arr[], int size) {
for(int i=0;i<size;i++) {
cout<<arr[i]<<" ";
}
cout<<endl;
}
void segregate(int arr[], int size) {
int l=0, h=size-1;
while(l<h) {
while(!(arr[l]%2) && l<size) {
l++;
}
while((arr[h]%2) && h >=0) {
h--;
}
swap(arr[l], arr[h]);
}
}
int main() {
int arr[] = {1,2,3,4,5,6,7,8,9};
int size = 9;
print(arr,size);
segregate(arr,size);
print(arr,size);
return 0;
}
I don't get the expected result
1 2 3 4 5 6 7 8 9
8 2 6 5 4 3 7 1 9
What am I missing?
What you're trying to do is also called partitioning. The standard library provides two algorithms to do just that: std::partition and std::stable_partition.
int main()
{
int arr[] = {1,2,3,4,5,6,7,8,9};
auto split = std::partition( std::begin(arr), std::end( arr ),
[]( int a ) { return ! a%2; } );
// [ begin, split ) are all even
// [ split, end ) are all odd
}
http://ideone.com/kZI5Zh
If you're still interesting in writing your own, cppreference's description of std::partition includes the equivalent code.
Your version is missing an if statement right before the swap. You should only swap when there is an odd on the left.
Problem 1:
You need to call the swap only if l has not crossed h, you are calling it always.
Consider the array {2,1}, which is already sgeregated.
Now after the two inner while loops l will be 1 and h will be 0. In your case you'll go ahead and swap, but a swap is not really needed since l has crossed h.
And when that happens the array is already segregated.
So change
swap(arr[l], arr[h]);
to
if(l<h) {
swap(arr[l], arr[h]);
}
Problem 2:
Also the order of conditions in your inner while loops must be reversed. You are checking
while(number at index l is even AND l is a valid index) {
l++;
}
which is incorrect. Consider an array {2,4}, now at some point in the above while loop l will be 2 and you go ahead and access arr[2], which does not exist.
What you need is:
while(l is a valid index AND number at index l is even) {
l++;
}
As simple as it gets:
void partitionEvenOdd(int array[], int arrayLength, int &firstOdd)
{
firstOdd = 0;
for (int i = 0; i < arrayLength; i++) {
if (array[i]%2 == 0) {
swap(array[firstOdd], array[i]);
firstOdd++;
}
}
}
Can't you just use standard sort?
Something like:
#include <stdio.h>
#include <stdlib.h>
int values[] = { 40, 10, 100, 90, 20, 25 };
int compare (const void * a, const void * b)
{
// return -1 a-even and b-odd
// 0 both even or both odd
// 1 b-even and a-odd
}
qsort (values, 6, sizeof(int), compare);
Related
This is my first post and hope I'm not doing anything wrong.
I am trying to write a program that find the first value of the vector that reach k-occurrences in it.
For example, given this vector and k=3:
1 1 2 3 4 4 2 2 1 3
I would see 2 as output, because 2 is the first number reaching the 3rd occurrence.
The following code is what I tried to run, but somehow output is not correct.
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> vettore;
int k;
int a,b,i;
int occ_a;
int occ_b;
cout<< "Write values of vector (number 0 ends the input of values)\n";
int ins;
cin>>ins;
while(ins)
{
vettore.push_back(ins); //Elements insertion
cin>>ins;
}
cout<<"how many occurrences?\n"<<endl;;
cin>>k;
if(k>0)
{
int i=0;
b = vettore[0];
occ_b=0;
while(i< vettore.size())
{
int j=i;
occ_a = 0;
a = vettore[i];
while(occ_a < k && j<vettore.size())
{
if(vettore[j]== a)
{
occ_a++;
vettore.erase(vettore.begin() + j);
}
else
j++;
}
if(b!=a && occ_b < occ_a)
b = a;
i++;
}
cout << b; //b is the value that reached k-occurrences first
}
return 0;
}
Hours have passed but I have not been able to solve it.
Thank you for your help!
Your code is difficult to read because you are declaring variables where they are not used. So their meanings is difficult to understand.
Also there is no need to remove elements from the vector. To find a value that is the first that occurs k-times is not equivalent to to change the vector. They are two different tasks.
I can suggest the following solution shown in the demonstrative program below.
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v = { 1, 1, 2, 3, 4, 4, 2, 2, 1, 3 };
size_t least_last = v.size();
size_t k = 3;
for ( size_t i = 0; i + k <= least_last; i++ )
{
size_t count = 1;
size_t j = i;
while ( count < k && ++j < least_last )
{
if ( v[j] == v[i] ) ++count;
}
if ( count == k )
{
least_last = j;
}
}
if ( least_last != v.size() ) std::cout << v[least_last] << '\n';
return 0;
}.
The program output is
2
The idea is to find the last position of the first element that occurs k-times. As soon as it is found the upper limit of the traversed sequence is set to this value. So if there is another element that occurs k-times before this limit then it means that it occurs the first compared with already found element.
I am trying to implement merge sort algorithm in C++. This is my code.Logic seems to be fine.
But the output I'm getting is garbage values.I'm not able to get where the problem is in the code.
I think my logic is correct but I'm not sure.
#include <iostream>
using namespace std;
void Merge(int A[],int L[],int nL,int R[],int nR);
void MergeSort(int A[]);
//Function to Merge Arrays L and R into A.
//nL = number of elements in L
//nR = number of elements in R.
void Merge(int A[],int L[],int nL,int R[],int nR)
{
// i - to mark the index of left subarray (L)
// j - to mark the index of right sub-raay (R)
// k - to mark the index of merged subarray (A)
int i=0;
int j=0;
int k=0;
while(i<nL && j<nR)
{
if(L[i]<=R[i])
{ A[k]=L[i];
i=i+1;
}
else
{ A[k]=R[j];
j=j+1;
}
k=k+1;
}
while(i<nL)
{ A[k]=L[i];
i=i+1;
k=k+1;
}
while(j<nR)
{ A[k]=R[j];
j=j+1;
k=k+1;
}
}
// Recursive function to sort an array of integers.
void MergeSort(int A[],int n)
{
if (n<2) return;//base condition.If the array has less than two
//elements, do nothing
int mid=n/2;
// create left and right subarrays
// mid elements (from index 0 till mid-1) should be part of left sub-
//array
// and (n-mid) elements (from mid to n-1) will be part of right sub-
//array
int left[mid];
int right[n-mid];
for(int i=0;i<mid-1;i++) left[i]=A[i];// create left subarray
for(int i=mid;i<n-1;i++) right[i-mid]=A[i];// create right subarray
MergeSort(left,mid);
MergeSort(right,n-mid);
Merge(A,left,mid,right,n-mid);
}
int main()
{ int A[]={2,4,7,1,5,3};
int n=sizeof(A)/sizeof(A[0]);
MergeSort(A,n);
for(int i=0;i<n;i++) cout<<A[i]<<" ";
return 0;
}
Expected output is 1 2 3 4 5 7
But actual is 0 -785903160 1 0(every time it's different)
This has been answered at, how-to-implement-classic-sorting-algorithms-in-modern-c. But I thought I'd post an answer that beginners my find valuable as I've seen this asked many times in the past. It must be a popular homework question.
In my opinion, if this is a modern C++ assignment, there should be a lot less of using indexing.
So in this implementation, I have not used std::merge and wrote the merge so some method could be seen.
Avoid the idiom: using namespace std; Why it is taught is beyond me. Typedef your types, it is much clearer.
using data_vect = std::vector<int>;
Hopefully this is clear enough and completely done with iterators. It is not as efficient as possible, the push_back in Merge could be avoided among other things. I DuckDucked this sort and the first few hits were not that great.
#include <iostream>
#include <vector>
using data_vect = std::vector<int>;
using dv_iter = data_vect::iterator;
data_vect Merge(data_vect& first, data_vect& second)
{
data_vect result;
dv_iter fval = first.begin();
dv_iter sval = second.begin();
for (;fval != first.end() || sval != second.end();)
{
if (fval == first.end())
result.push_back(*sval++);
else if (sval == second.end())
result.push_back(*fval++);
else if (*fval < *sval)
result.push_back(*fval++);
else
result.push_back(*sval++);
}
return result;
}
void MergeSort(data_vect& input)
{
int half = input.size() / 2;
if (! half)
return;
data_vect left(input.begin(), input.begin() + half );
data_vect right(input.begin() + half, input.end());
MergeSort(left);
MergeSort(right);
input = Merge(left, right);
}
int main()
{
data_vect A = { 6,2,7,4,1,5,3 };
MergeSort(A);
for ( auto& val : A )
std::cout << val << " ";
return 0;
}
Although understandable,
it is not possibile in C++ to declare an array with a variable size, e.g. int[mSize].
All arrays must have a constant size, e.g. int[10] or
const int mSize = 10;
int[mSize] mArray...
You want a storage container which has a variable size. as #PaulMcKenzie suggested,
you might want to use a Vector object. Your code would look something like this:
#include <iostream>
#include <vector>
using namespace std;
void Merge(vector<int>& A, vector<int>& L, vector<int>& R);
void MergeSort(vector<int>& A);
//Function to Merge Arrays L and R into A.
void Merge(vector<int>& A, vector<int>& L, vector<int>& R)
{
// i - to mark the index of left subarray (L)
// j - to mark the index of right sub-raay (R)
// k - to mark the index of merged subarray (A)
unsigned int i=0;
unsigned int j=0;
unsigned int k=0;
while(i<L.size() && j<R.size())
{
if(L[i]<=R[i])
{ A[k]=L[i];
i=i+1;
}
else
{ A[k]=R[j];
j=j+1;
}
k=k+1;
}
while(i<L.size())
{ A[k]=L[i];
i=i+1;
k=k+1;
}
while(j<R.size())
{ A[k]=R[j];
j=j+1;
k=k+1;
}
}
// Recursive function to sort an array of integers.
void MergeSort(vector<int>& A)
{
int n = A.size();
if (n<2) return;//base condition.If the array has less than two
//elements, do nothing
int mid=n/2;
// create left and right subarrays
// mid elements (from index 0 till mid-1) should be part of left sub-
//array
// and (n-mid) elements (from mid to n-1) will be part of right sub-
//array
vector<int> left(mid);
vector<int> right(n-mid);
for(int i=0;i<mid;i++) left[i]=A[i];// create left subarray
for(int i=mid;i<n;i++) right[i-mid]=A[i];// create right subarray
MergeSort(left);
MergeSort(right);
Merge(A,left,right);
}
int main()
{ vector<int> A={2,4,7,1,5,3};
MergeSort(A);
for(unsigned int i=0;i<A.size();i++) cout<<A[i]<<" ";
return 0;
}
[Edit]
I noticed I accidentally used comma's instead of dots in vector.size() calls. Also, I noticed 2 arrays stopping one item too early in copying left and right vectors.
Your code did not work. Above code compiles fine, but produces 1 3 5 2 4 7 as output. Also, have you thought of a vector of uneven length, such as 5 4 3 2 1?
At this point, the code will not split properly
I am trying to get the nth largest number of an array, I tried to sort the array then access the nth number by indexing; I have written this code:
#include <iostream>
using namespace std;
int largest(int a[],int k){
for (int i=0;i<=(sizeof(a)/sizeof(*a));i++){
for (int j=i+1;j<=(sizeof(a)/sizeof(*a));j++){
if(a[j]>a[i]){
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
return a[k-1];
}
int main()
{
int a[]={3,2,1,0,5,10};
int m=largest(a,4);
cout<<m<<endl;
return 0;
}
and when I print out m it appears to be 5 while it is expected to be 2, when I tried to replace int m=largest(a,4); with m=largest(a,1); it printed 2 so it appears that he prints the index of the array a but without sorting it, any idea?
The problem lies in the use of sizeof(a)/sizeof(*a) to get the number of elements of the array. sizeof(a) is the size of a pointer.
You need to pass the size of the array to the function.
int largest(int a[], int size, int k){
for (int i=0;i<size;i++){
for (int j=i+1;j<size;j++){
...
}
}
}
and call it with
int m = largest(a, 6, 4);
There are three problems with your code.
First, when you pass the array as an argument to your function, it decays into a pointer. So the function can never know the size of the array without additional information. It is main()'s job to find the size of the array and pass that information along to largest().
Second, you have an off-by-one error in your code, because you are attempting to iterate from 0 to the number of elements in the array.
The following will work:
#include <iostream>
using namespace std;
int largest(int a[],int k, int n){
for (int i = 0; i < n; i++){
for (int j = i + 1; j < n; j++){
if (a[j] > a[i]){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[k-1];
}
int main()
{
int a[] = {3, 2, 1, 0, 5, 10};
int k = 4;
int m = largest(a, k, sizeof a/ sizeof *a);
cout << m << endl;
}
At last but not least, you have nasty side effects in your function. If you have a function that is supposed to find the largest element of the array, it shouldn't modify the entire array in order to do so.
You can make a copy of the original array and sort it. Or you can implement a k-element sort algorithm. Either way you shouldn't change user data just to find some statistic from it.
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[]={3,2,1,0,5,10};
std::sort(a, a+6, greater<int>() ); // Sort an array of 6 elements in greatest-first order.
cout<<a[3]<<endl; // Show the 4th element from the front.
return 0;
}
UPD: There are STL algorithm to use: std::nth_element.
#include <iostream>
#include <algorithm>
int main(){
int arr[] = {54, 897, 87, 4, 6,987};
size_t length = 6, k = 3;
std::cout<<std::nth_element(arr, arr + k, arr + length, std::greater<int>());
}
Also, if you want to implement it by yourselt you can do such thing based on quick sort:
#include <iostream>
#include <algorithm>
template<class T>
T largest_k(T* a, size_t left, size_t right, size_t k) {
if(left>=right)
return a[k-1];
size_t i = left, j = right;
T middle = a[ i + (j-i) / 2 ];
do {
while ( a[i] > middle ) i++;
while ( a[j] < middle ) j--;
if (i <= j) {
std::swap(a[i], a[j]);
i++; j--;
}
} while ( i<=j );
// We need to go deeper only for needed part of a
if ( k<=j+1 )
return largest_k(a, left, j, k);
if ( k>= i )
return largest_k(a, i, right, k);
}
int main()
{
int arr[] = {54, 897, 87, 4, 6,987};
size_t length = 6, k = 3;
std::cout<<largest_k<int>(arr, 0, length-1, k);
}
I have written the following code for Heap Sort using Max-Heap logic.
#include<bits/stdc++.h>
#include<algorithm>
#include<vector>
using namespace std;
void max_heapify(vector<int> &a,int i)
{
int left=2*i+1;
int right=2*i+2;
if(i >= (int)a.size()/2 )
{
return;
}
int max=i;
if(a[i]<a[left])
{
max=left;
}
if(a[max]<a[right])
{
max=right;
}
if(max!=i)
{
swap(a[i],a[max]);
max_heapify(a,max);
}
}
void build_maxHeap(vector<int> &a)
{
int l=a.size();
for(int i=l/2-1;i>=0;i--)
{
max_heapify(a,i);
}
}
void heap_sort(vector<int> &a)
{
build_maxHeap(a); // max element at top.
for(int i=a.size()-1;i>=1;i--)
{
swap(a[i],a[0]);
cout<<a[i]<<" ";
a.pop_back();
max_heapify(a,0);
}
cout<<a[0]<<endl;
}
int main()
{
vector<int> a={6,7,8,1,2,9,32};
heap_sort(a);
return 0;
}
Output : 32 9 32 7 32 32
Expected Output: Print elements in descending order.
I don't know why there is a repetition of 32. I am popping the element from the end but can't figure out why such behavior.
in short: you do not handle case when left is inside vector, but right is not.
more in depth explanation:
in heap_sort after a.pop_back() a.size() is 6, calling max_heapify(a, 0), may, in turn call max_heapify(a, 2) , and when you call max_heapify(a, 2), and a.size() is 6, right will be 2*2+2 == 6, so you will attempt to access out of range for vector a (and there seems to be value 32 you popped from vector).
You have a bug in your max_heapify.
void max_heapify(vector<int> &a,int i)
{
int left=2*i+1;
int right=2*i+2;
if(i >= (int)a.size()/2 )
{
return;
}
int max=i;
if(a[i]<a[left])
{
max=left;
}
// Bug is here
if(a[max]<a[right])
{
max=right;
}
if(max!=i)
{
swap(a[i],a[max]);
max_heapify(a,max);
}
}
You always check a[max] < a[right], even if right >= size. So you can have this situation:
size = 2
i = 0
left = 1
right = 2
And the array contains: [0,1,3, ...]
Because you don't check to see if right >= size, the '3' will get re-inserted into your heap.
#include <iostream>
using namespace std;
class A
{
public:
int index;
int t;
int d;
int sum;
};
A arr[1000];
bool comp (const A &a, const A &b)
{
if (a.sum < b.sum)
return true;
else if (a.sum == b.sum && a.index < b.index)
return true;
return false;
}
int main (void)
{
int n,foo,bar,i;
i = 0;
cin>>n;
while ( n != 0 )
{
cin>>foo>>bar;
arr[i].index = i+1;
arr[i].t = foo;
arr[i].d = bar;
arr[i].sum = arr[i].t+arr[i].d;
n--;
i++;
}
sort(arr,arr+n,comp);
for ( int j = 0; j < n; j++ )
cout<<arr[j].index;
cout<<"\n";
return 0;
}
So, I made this program which accepts values from users, and then sorts them on the basis of a specific condition. However, when I try to print the values of the array, it doesn't print it. I don't know why. Please help. Thanks!
PS: I even tried to print the value of the array without use of comparator function, but still it doesn't print.
Edit: Got my error, as mentioned by some amazing people in the comments. However, on inputting the values as,
5
8 1
4 2
5 6
3 1
4 3
It should return the answer as 4 2 5 1 3 but instead it returns 1 2 3 4 5. Basically, it sorts according to the sum of the 2 elements in each row and prints the index. What might be the problem?
It is not sorting because you are modifying the value of n in the while loop.
So, when n = 0 after the loop ends, there is nothing to sort (or to print later for that matter):
sort( arr, arr + n, comp);
is equivalent to
sort( arr, arr + 0, comp);
Easiest approach would be to use a for loop:
for( int i=0; i<n; ++i )
{
....
}
This way, n remains unchanged.