Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- # define N 10
- double TotalAvg(int a[]);
- double UpdateAvg(int a[], double avg, int number, char op, int index);
- int FindBestPartition(int a[]);
- int main()
- {
- int i=0, partition=-1;
- int a[N] = {0};
- printf("Please enter %d elements to find their best partition:\n", N);
- for(i=0; i<N; i++)
- {
- scanf("%d", &a[i]);
- }
- partition = FindBestPartition(a);
- printf("Best partition for the given array is at index: %d\n", partition);
- return 0;
- }
- double TotalAvg(int a[])
- {
- /*sum=the value of all the index in the array, index for the for*/
- double sum=0;
- int i;
- for(i=0;i<N;i++)
- sum+=a[i];
- return sum/N;
- }
- /*עבור + מעדכנת את הממוצע עם הוספת איבר חדש*/
- /*עבור - מעדכנת את הממוצע על החסרת איבר*/
- /*if op=- and number=0 the function return that the update avg is 0*/
- double UpdateAvg(int a[], double avg, int number, char op, int index)
- {
- if(op=='+')
- {
- return ((avg*number+(double)a[index])/(double)(number+1));
- }
- else
- {
- if(number==1)return 0;
- return ((avg*number-(double)a[index])/(double)(number-1));
- }
- }
- int FindBestPartition(int a[])
- {
- /*max הוא האינדקס עבורו ההפרש מקסימלי*/
- /*avgR=average of the right side,avgL=average of left side*/
- /*index=האיבר עבורו ההפרש הכי גדול*/
- /*הפעולה מוצאת את ההפרש המקסימלי בין ממוצע שמאל לממוצע ימין ומחיזרה את האינדקס שבוא זה מתרחש*/
- /*בלולאה אני מעדכן את ממוצע ימין וממצו שמאל באזרת הפונקציה UpdateAvg*/
- int i=0,index=0;
- double avgR=UpdateAvg(a,TotalAvg(a),N,'-',0),avgL=a[0],max,hefresh;
- hefresh=avgL-avgR;
- if(hefresh<0)hefresh=hefresh*(-1);
- max=hefresh;
- for(i=1;i<N;i++)
- {
- avgL=UpdateAvg(a,avgL,i,'+',i);
- avgR=UpdateAvg(a,avgR,N-i,'-',i);
- hefresh=avgL-avgR;
- if(hefresh<0)hefresh=hefresh*(-1);
- if(hefresh>max)
- {
- max=hefresh;
- index=i;
- }
- }
- return index;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement