Is it possible to arrange the array made up of only 1\'s and 0\'s in descending order within one parse without using auxiliary array?
For example: Suppose you have an ar
Just an other way of it .
Have two pivots one from beginning and other at end like the bellow one ,
for(int i=0, j=n-1;i<j;)
{
if(a[i]==1 && a[j]==0) swap(a[i],a[j]);
else if(a[i]==1 && a[j]==1) j--;
else if(a[i]==0 && a[j]==0) i++;
else if(a[i]==0 && a[j]==1) {j--; i++;}
}
for (size_t i = 0, count = 0; i < n; i++) {
if (a[i] == 1) a[count++] = 1;
if (i >= count) a[i] = 0;
}
Give it a try!
(read comments):
#include<stdio.h>
int main(void){
int a[]={1,0,0,0,1,0,1};
int n = 7,
i,
index = 0;
while(index < n && a[index]) index++; // skip initial 1's
for(i = index; i < n; i++){
if(a[i]) a[index++] = 1; // if `1` at a[i] make its 0 and
a[i] = 0; // make at index 1.
}
for(i = 0; i < n; i++){
printf("%3d", a[i]);
}
return 1;
}
Check working code @ideone's links:
Case-1: {1,0,0,0,1,0,1}
Case-2: {1,0,1,1,1,0,0,1,0,1, 1}
Case-3: {1,1,1,1,1,1,1}
Case-4: {0, 0, 0, 0, 0, 0, 0}
Case-5: {0, 0, 0, 1, 1, 1, 1}
So I think it works correct!
its simple, it need only n
iterations.
complexity wise O(n)
.
Let me try this:
void arrange(int a[],int n)
{
int* p = a;
int* q = &a[n-1];
while (p <= q)
{
while (*p == 1 && p <= q) /* Find a Zero, starting from the front */
{
++p;
}
while (*q == 0 && p <= q) /* Find a One, starting from the back */
{
--q;
}
if (p < q) /* *p == Zero, and *q == One, and p is to the left of q. */
{
*p = 1;
*q = 0;
}
}
}
This works with two pointers, one starting at the front, the other starting at the back, and they both move towards the middle until they meet.
Along the way, if the two pointers find a 0 on the left and a 1 on the right, swap the values, then continue.
(code is untested, but the outline seems solid)
How about recursion? Simple and elegant, as always.
void countAndRewrite(int arr[], size_t n, size_t *cone, size_t total)
{
if (n) {
if (arr[0])
++*cone;
countAndRewrite(arr + 1, n - 1, cone, total);
arr[0] = total - n < *cone;
}
}
int main()
{
int arr[] = { 0, 1, 0, 1, 1, 1, 0 };
size_t cone = 0;
countAndRewrite(arr, 7, &cone, 7);
for (size_t i = 0; i < 7; i++)
printf("arr[%zu] = %d\n", i, arr[i]);
return 0;
}
#include<iostream>
using namespace std;
int main() {
int arr[] = {1, 1, 1, 1, 1, 0, 0, 0};
int N = sizeof(arr) / sizeof(arr[0]);
int p = 0, q = 1;
while (q != N) {
if (arr[p] > arr[q]) {
arr[p] = 0;
arr[q] = 1;
p++;
q++;
}
else {
q++;
if (arr[p] == 0)
p++;
}
}
for (int i = 0; i < N; i++)
cout << arr[i];
return 0;