-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathminimum_xor_value.c
63 lines (56 loc) · 1.5 KB
/
minimum_xor_value.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
Minimum XOR value problem in C
Given an integer array A of N integers, find the minimum XOR value made by a pair of integers in the array.
*/
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
//Comparator function used by qsort
int compare(const void *a, const void *b)
{
return (*(int *)a - *(int *)b);
}
void min_xor(int *arr, int n)
{
//Temporary variables to store the pair of elements
int a, b;
//res will store the minimum xor value
int res = INT_MAX;
for (int i = 0; i < n - 1; i++)
{
//x will store xor value for each possible pair of elements of array
int x = arr[i] ^ arr[i + 1];
if (x < res)
{
res = x;
a = arr[i];
b = arr[i + 1];
}
}
printf("The Minimum xor value is : %d \n", res);
printf("The corresponding pair of elements are : %d and %d ", a, b);
}
int main()
{
//Input the size of the array
int n;
printf("Enter the size of array : ");
scanf("%d", &n);
printf("Enter the array : ");
int arr[n];
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
//Sort the array in ascending order
qsort(arr, sizeof(arr) / sizeof(*arr), sizeof(*arr), compare);
min_xor(arr, n);
return 0;
}
/*
Time Complexity : O(n * logn), where 'n' is the size of the array
Space Complexity : O(1)
SAMPLE INPUT AND OUTPUT
Enter the size of array : 4
Enter the array : 1 2 3 4
The Minimum xor value is : 1
The corresponding pair of elements are : 2 and 3
*/