Arranging numbers with duplicate entries
#include<stdio.h>
int main(){
int a[9],i,j,r,t,min,c=0;
for(r=0;r<9;r++)
scanf("%d",&a[r]);
for (j=0;j<9;j++) {
min=a[j];
for(i=j;i<9;i++) {
if(a[i] < min ) {
c=i;
min=a[i];
}
}
t=a[j];
a[j]=min;
a[c]=t;
}
for(r=0;r<9;r++)
printf("%d",a[r]);
}
This is the code that should arrange the numbers entered by the user in ascending order. If input is 1 2 3 2 4 1 5 6 3 output is 1 1 2 2 3 3 4 5 6, but I want the result to be 1 2 3 4 5 6 i.e. Duplicate entries have been deleted. Please help me.
If a range of numbers is given, you can do so using a boolean array that will be stored 1
at the appropriate element index.
#include <stdio.h>
#include <stdbool.h>
#define NUM_RANGE 10
int main(){
int num;
bool freq[NUM_RANGE + 1] = {0};
for(int r = 0; r < 9; r++){
scanf("%d",&num);
freq[num] = 1;
}
for (int i = 0; i < NUM_RANGE + 1; i++)
if(freq[i])
printf("%d ", i);
}
source to share
#include<stdio.h>
int main(){
int a[] = {1, 2, 3, 2, 4, 1, 5, 6, 3};
int n = sizeof(a)/sizeof(*a);
int i, j, t;
for (j=0;j<n-1;j++){
for(i=j+1;i<n;){
if(a[i] == a[j]){
t = a[i];
a[i] = a[--n];
a[n] = t;
continue;
}
if(a[i] < a[j]){
t = a[i];
a[i] = a[j];
a[j] = t;
}
++i;
}
}
for(i=0;i<n;i++)
printf("%d ", a[i]);
return 0;
}
source to share
So this is the procedure that you can follow.
-
You are sorting your array (as you already did). Your sorting algorithm has O (n ^ 2) worst-case execution time, where n is the number of elements in your array. If you are interested in uptime, the optimal uptime that can be achieved is O (n logn) [MergeSort].
-
Then we need to find the duplicates and remove them. Since you already ordered them to just iterate over your array and check that each number a [i] and the next number a [i + 1] are different. If it isn't, remove it and fill in the empty space by moving all other arrays forward.
So:
for(i = 0; i < 9; i++){
if(a[i] == a[i+1]){
deletNumber(i); //deletes number at position i in the array and shifts the
//rest of the array so the empty space is filled.
}
}
void deleteNumber(int i){
int j;
for(j = i; j<8; j++){
a[j] = a[j++];
}
}
source to share