I think I've just found a solution to your problem. In what follows I will list the whole code with comments to make it easier to follow.
#include <stdio.h> int main() { // input no. of students int n, i; printf("no. of students = "); scanf("%d", &n); // allocate an array for exactly "n" marks int *marks = new int[n]; // input marks printf("marks: "); for (i = 0; i < n; i++) scanf("%d", &marks[i]); // compute frequencies int freq[101] = {0}; for (i = 0; i < n; i++) freq[marks[i]]++; // display non-zero frequencies printf("\nMark Frequency\n\n"); for (i = 0; i < 101; i++) if (freq[i]) printf("%d %d\n", i, freq[i]); // display all intervals between identical marks printf("\nIntervals\n\n"); int pos[101] = {0}; for (i = 0; i < n; i++) { if (pos[marks[i]]) printf("%d %d\n", marks[i], i - pos[marks[i]]); pos[marks[i]] = i + 1; } printf("\n"); // free memory used by the marks[] array delete[] marks; return 0; }
I've tried inputing your example and here is what has been displayed (notice that the frequencies are displayed considering the ascending order of the marks).
no. of students = 10 marks: 46 37 28 87 76 83 76 38 76 37 Mark Frequency 28 1 37 2 38 1 46 1 76 3 83 1 87 1 Intervals 76 1 76 1 37 7
The algorithm I've used is very quick even for a large number of marks. It goes two times through the elements of the marks array - one time to compute the frequencies and the other to find the intervals. Thus the algorithm has linear complexity. As you may have noticed I've used two additional arrays "freq" and "pos" of 101 elements, which help at minimising the total running time.
Please let me know if you understand how the algorithm works or not. I am ready to give you any further information concerning the algorithm or the C implementation.
Login