Mam powiedzmy tablice 10 elementową i podaną jedną konkretną wartość. Muszę posortować elementy tak, żeby wartości mniejsze od tego podanego były przed nim, a większe lub równe, za nim, ale bez zmiany układu. Powiedzmy, że mam tab[]={5,6,8,2,6,9,5,6,4,5} i np dla 6 ta tablica ma wyglądać tak tab[]={5,2,5,4,5,6,8,6,9,6}. Jak napisać taką funkcję?
0
0
To nie tyle sortowanie, co kopiowanie z granicą.
Kopiowanie jest proste - o ile umiesz programować.
1
W C++ mógłbyś użyć po prostu std::stable_partition
. W C musisz ręcznie iterować i swapować.
1
Zacznij od:
static void _IntArrayStablePartitionWithTmpArray(int *a, int count, bool (*f)(int), int *tmp)
{
int tmpCount = 0;
while (count--) {
if (f(*a))
..... // do it yourself
....
++a;
}
memcpy(a, tmp, sizeof(*a) * tmpCount);
}
void IntArrayStablePartition(int *a, int count, bool (*f)(int))
// albo IntArrayStablePartition(int *a, int count, int lessThenValue)
// albo IntArrayStablePartition(int *a, int count, bool (*f)(int, void *), void* ctx)
{
int *tmp = malloc(sizeof(int[count]));
IntArrayStablePartitionWithTmpArray(a, count, tmp, f);
free(tmp);
}