Я напишу функцию, чтобы проверить, имеют ли 2 массива одинаковые элементы. но я хочу сделать рекурсивную функцию для проверки этого. у вас есть идеи для этого? например здесь массива AB и выход:Рекурсивный способ проверить, имеют ли 2 массива одинаковые элементы
A: [2 4 5 4]
B: [4 5 2 4]
из положить 1
вне положенный должно быть 1, если то же самое и 0, если нет.
здесь моя регулярная функция:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <assert.h>
int partition(int *a, int left, int right)
{
int first = left;
int pivot;
int pos;
srand((unsigned)time(NULL));
pos = rand() % (right - left + 1) + left;
swap(a + first, a + pos);
pivot = a[first];
while (left<right)
{
while (a[right] > pivot) right--;
while ((left < right) && (a[left] <= pivot)) left++;
if (left < right)
swap(a + left, a + right);
}
pos = right;
a[first] = a[pos];
a[pos] = pivot;
return pos;
}
void quick_sort(int *a, int first, int last)
{
int pos;
if (first<last)
{
pos = partition(a, first, last);
quick_sort(a, first, pos - 1);
quick_sort(a, pos + 1, last);
}
}
int *input_array_dyn(int n)
{
int i;
int *a;
a = (int *)calloc(n, sizeof(int));
assert(a);
printf("enter the array of length %d\n", n);
for (i = 0;i<n;i++)
scanf_s("%d", a + i);
return a;
}
int part1_excute(int *a, int *b, int n)
{
int index;
int ans = 1;
quick_sort(a, 0, n - 1);
quick_sort(b, 0, n - 1);
for (index = 0;index<n;index++)
{
if (a[index] != b[index])
ans = 0;
}
if (ans == 0) return 0;
else return 1;
free(a);
free(b);
}
void main()
{
int *a, *b;
int ans = 1;
int size;
printf("Please input the size of array\n");
scanf_s("%d", &size);
printf("First array:\n");
a = input_array_dyn(size);
printf("Second array:\n");
b = input_array_dyn(size);
printf("If the output is 1, the arrays are the same.\n");
printf("If the output is 0, the arrays are the not same.\n");
printf(" The ans is: %d\n", part1_excute(a,b,size));
}
Почему рекурсивный? BTW quicksort _is_ уже рекурсивный. –
Зачем переустанавливать сортировку? Просто используйте 'qsort()', если то, что вы пытаетесь выполнить, - простое сравнение. – unwind
'free (a); бесплатно (б); 'Никогда не достигайте этого момента. – BLUEPIXY