What is the most efficient way to find all combinations of n choose 2
for 2 <= n <= 100000
?
For example, 5 choose 2
is
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
This is what I have so far for testing the worst case:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_ITEMS 100000
void combinations(int[], int);
long long count = 0;
int main(void) {
int *arr = (int*) calloc(MAX_ITEMS, sizeof(int));
if (!arr) {
printf("Error allocating memory.");
exit(1);
}
int i, n = MAX_ITEMS;
for (i = 0; i < MAX_ITEMS; i++) {
arr[i] = i + 1;
}
clock_t start, diff;
int msec;
start = clock();
combinations(arr, n);
diff = clock() - start;
msec = diff * 1000 / CLOCKS_PER_SEC;
printf("\n\nTime taken %d seconds %d milliseconds", msec / 1000, msec % 1000);
printf("\n\nPairs = %lld\n", count);
return 0;
}
void combinations(int arr[], int n) {
int i, j, comb1, comb2, end = n - 1;
for (i = 0; i < end; i++) {
for (j = i + 1; j < n; j++) {
// simulate doing something with data at these indices
comb1 = arr[i];
comb2 = arr[j];
// printf("%d %d\n", arr[i], arr[j]);
count++;
}
}
}
OUTPUT
Time taken 28 seconds 799 milliseconds
Pairs = 4999950000
I could be mistaken but time complexity is O(n^2).
Is there a more efficient algorithm to handle the worst case?