Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save TamojitSaha/8080262437bb4a2e49e390cdcb381c67 to your computer and use it in GitHub Desktop.
Save TamojitSaha/8080262437bb4a2e49e390cdcb381c67 to your computer and use it in GitHub Desktop.
#include <stdio.h>
void merge(int *arr, int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void bubbleSort (int *a, int n)
{
int out, in, swapper;
for (out = 0; out < n; out++)
{ // outer loop
for (in = out; in < (n - 1); in++)
{ // inner loop
if (a[in] > a[in + 1])
{ // out of order?
// swap them:
swapper = a[in];
a[in] = a[in + 1];
a[in + 1] = swapper;
}
}
}
}
void bubbleSort (int *a, int n)
{
int out, in, swapper;
for (out = 0; out < n; out++)
{ // outer loop
for (in = out; in < (n - 1); in++)
{ // inner loop
if (a[in] > a[in + 1])
{ // out of order?
// swap them:
swapper = a[in];
a[in] = a[in + 1];
a[in + 1] = swapper;
}
}
}
}
int movingAvg (int *ptrArrNumbers, long *ptrSum, int pos, int len, int nextNum)
{
//Subtract the oldest number from the prev sum, add the new number
*ptrSum = *ptrSum - ptrArrNumbers[pos] + nextNum;
//Assign the nextNum to the position in the array
ptrArrNumbers[pos] = nextNum;
//return the average
return *ptrSum / len;
}
int main ()
{
int sample[] = { 50, 10, 20, 18, 20, 100, 18, 10, 13, 500, 50, 40, 10 };
int size = sizeof (sample) / sizeof (sample[0]);
bubbleSort (sample, size);
for (int i = 0; i < size; i++)
{
printf ("arr[%d]: %d\n", i, sample[i]);
}
int arrNumbers[5] = { 0 };
int pos = 0;
int newAvg = 0;
long sum = 0;
int len = sizeof (arrNumbers) / sizeof (int);
for (int i = 0; i < size; i++)
{
newAvg = movingAvg (arrNumbers, &sum, pos, len, sample[i]);
printf ("The new average is %d\n", newAvg);
pos++;
if (pos >= len)
{
pos = 0;
}
}
return 0;
}
@TamojitSaha
Copy link
Author

@sandeepansg
Here you go...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment