Here’s the problem I’ve been trying to tackle for a few days.
I need to write a program that gets a sorted array. The program will put 999 where two adjacent blocks have the same value, and then put all the 999 in the end of the array. I need to do this without using another array and the program must be O(n).
example input:
50,60,60,72,81,81,81,81,93,93
desired output:
50,60,72,81,93,999,999,999,999,999
another example:
1,1,2,3,4,4,5,6,6
desired output:
1,2,3,4,5,6,999,999,999
my code. It’s not working. For the first example the output is alright. for the second example i get 1,2,3,4,5,4,5,6,-14568127 (out of array bounds)
my algorithm is i walk through the array with two indexes, i and j, if a[i]!=a[i+1] then i advance i. if they are equal, j looks for the next unique value, and puts it in a[i+1].
I’d love to hear better ideas or a code to do this. in C.
while((j!=size-1)&&(a[size-1]!=a[i]))
{
if(a[i]!=a[i+1])
{
i++;
j=i;
}
if(a[i]==a[i+1])
{
j=i;
while(a[i]==a[j])
j++;
a[i+1]=a[j];
i++;
if(j!=size-1)
j=i;
}
}
i++
for(;i<size;i++)
a[i]=999;
I’ve edited the code, now I do it as chen suggested. First i iterate through the array putting 999 where the doubles are, problem arises when I want to switch though. here’s the code I wrote for re-sorting the array:
each time i put a 999 somewhere, count++.
It’s working for the two examples I gave perfectly. Thanks everyone.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
void main()
{
int *a;
int i=0,j=0,size,count=0;
printf("Enter the size of the array\n");
scanf("%d", &size);
a=(int *)calloc(size,sizeof(int));
printf("Enter %d numbers\n",size);
for(i=0;i<size;i++)
scanf("%d",&a[i]);
printf("The array recieved is :\n");
for(i=0;i<size;i++)
printf(" %d ", a[i]);
i=0;
printf("\n");
for(i=0;i<size;i++)
{
if(a[i]==a[i+1])
{
j=i+1;
while(a[i]==a[j])
{
a[j]=999;
j++;
}
count++;
}
}
while(count!=0)
{
for(i=0;i<size-1;i++)
{
j=i;
if(a[j]==999)
{
a[j]=a[j+1];
a[j+1]=999;
}
}
count--;
}
printf("The new array is: \n");
for(i=0;i<size;i++)
printf(" %d ",a[i]);
free(a);
getch();
}
Here’s a general approach that runs in O(n):
Assumption: The input array does not contain
999(It’s fine if it does, you just have to use a different sentinel value):999999until you hit a different element.999‘s at the end, so now, keep 2 separate pointers:Xto keep track of where the first999is in the arraynumto keep track of where we are in the swapping process999using these two pointers.This might sound confusing, so here’s a pseudo animation using one of your examples:
(Using
Was the sentinel in place of ‘999` for readability)And again, but labeling the
Wwith numerical suffix this time so you can see which swaps are happening: