For example i have an array {1,2,2,2,3,3,3,3,4,4,4,4,4,} I need to transform it into {4,4,4,4,4,,3,3,3,3,2,2,2,1} So i have to sort it by the number of repetitions of an array element somehow. I saw some solves of this problem on c but i have to write it on C. I can`t use vector or smth. Just Sorting with buffer array or inside of exact array.
I tried something like this, but honestly now i etched into a dead end: It is dont work properly as i ment. I have an algoritm in my head:
- Program count how times some element was repeated and write in into a second array
- Program sort second array
- Program sort first array by second array somehow
#include <stdio.h>
int main()
{
const int size = 10;
int A[size], B[size];
int counter1, counter2 = -1;
int temp = 0;
for (int i = 0; i < size; i ) {
printf("Enter %d element of array: ", i 1);
scanf_s("%d", &A[i]);
}
for (int i = 0; i < size-1; i ) {
counter1 = 0;
counter2 ;
for (int j = i; j < size; j ) {
if (A[j] == A[j - 1]) {
break;
}
if (A[j] == A[j 1]) {
counter1 ;
B[counter2] = counter1;
temp = A[i];
}
}
}
for (int i = 0; i < size; i ) {
printf("El %d = %d\n",i 1,B[i]);
}
}
CodePudding user response:
Not the best, but it does the job! I'm storing the final result in the Result[len][2];
variable! you can modify the code as you like
#include <stdio.h>
#include <string.h>
int main( )
{
int array[] = {1,2,2,2,3,3,3,3,4,4,4,4,4,11,10,6,6,6,6,6,6,6,6,6,6,6,6,};
int i,j,k=0,l,len,flag=0,temp0, temp1;
len = sizeof(array)/sizeof(array[0]);
int Result[len][2];
memset(Result,0,sizeof(Result));
for (i = 0 ;i < len ; i )
{
if (k != 0)
{
for (l= 0 ;l < k ; l )
if (array[i]== Result[l][0]) goto skip;
}
for(j= i ; j < len ; j )
{
if (array[i] == array[j])
{
Result[k][0] = array[j];
Result[k][1] ;flag = 1;
}
}
skip: if (flag == 1) {k ; flag = 0;}
}
for (i = 0; i < k; i )
{
for(j= i 1 ; j < k ; j )
{
if(Result[i][1] < Result[j][1])
{
temp0 = Result[i][0];
temp1 = Result[i][1];
Result[i][0] = Result[j][0];
Result[i][1] = Result[j][1];
Result[j][0] = temp0 ;
Result[j][1] = temp1 ;
}
}
}
for (i = 0; i < k; i ) printf("[%d][%d]\n",Result[i][0],Result[i][1]);
return 0;
}
The output at my computer under the Linux environment is as follows:
[6][12]
[4][5]
[3][4]
[2][3]
[11][1]
[10][1]
[1][1]
CodePudding user response:
how can I sort an array by the number of repetitions
Sort array
A
of sizem
by value .Walk array and count number of different values:
n
Allocate array
B[]
of sizen
ofstruct
s that has 2 members: value and occurrence.Walk array
A[]
again and populateB[]
Sort
B[]
by.occurrence
.Walk
B[]
and re-populateA[]
.
O(m) memory, O(m *log m) time.