To check if two arrays have the same elements regardless of order in C, you can sort both arrays and then compare them element by element.
In this example,
arr1
and arr2
with the same elements but in different order.qsort
function from the stdlib.h
library.arraysEqual
that checks if the sorted arrays are equal.arraysEqual
to compare the arrays and print the result to the console.#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
int arraysEqual(int arr1[], int arr2[], int size) {
qsort(arr1, size, sizeof(int), compare);
qsort(arr2, size, sizeof(int), compare);
for (int i = 0; i < size; i++) {
if (arr1[i] != arr2[i]) {
return 0;
}
}
return 1;
}
int main() {
int arr1[] = {1, 2, 3};
int arr2[] = {3, 1, 2};
int size = sizeof(arr1) / sizeof(arr1[0]);
int isEqual = arraysEqual(arr1, arr2, size);
printf("%s\n", isEqual ? "true" : "false");
return 0;
}
true
In this example,
arr3
and arr4
with different elements.qsort
function from the stdlib.h
library.arraysEqual
that checks if the sorted arrays are equal.arraysEqual
to compare the arrays and print the result to the console.#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
int arraysEqual(int arr1[], int arr2[], int size) {
qsort(arr1, size, sizeof(int), compare);
qsort(arr2, size, sizeof(int), compare);
for (int i = 0; i < size; i++) {
if (arr1[i] != arr2[i]) {
return 0;
}
}
return 1;
}
int main() {
int arr3[] = {1, 2, 3};
int arr4[] = {4, 5, 6};
int size = sizeof(arr3) / sizeof(arr3[0]);
int isEqual = arraysEqual(arr3, arr4, size);
printf("%s\n", isEqual ? "true" : "false");
return 0;
}
false
In this tutorial, we learned How to check if Two Arrays have Same Elements (Regardless of Order) in C language with well detailed examples.