C說話完成最年夜間隙成績實例。本站提示廣大學習愛好者:(C說話完成最年夜間隙成績實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C說話完成最年夜間隙成績實例正文
本文實例展現了C說話完成最年夜間隙成績的辦法,關於算法的設計有必定的自創價值。分享給年夜家供年夜家參考。詳細以下:
成績描寫以下:
給定n個實數x1,x2,...,xn,求這n個實數在實軸上相鄰2個數之間的最年夜差值,請求設計線性的時光算法。
處理思緒:
留意題中請求設計線性時光算法。假如沒有這個請求,便可以先排序,找出來就很便利。但我們曉得排序最優秀的算法的時光效力也是nlogn的。所以弗成行。
采取一種區間算法。詳細步調就不說了,給出C說話代碼,有正文加以解釋。
詳細完成代碼以下:
#include "stdio.h"
#include "stdlib.h"
#define MAX 10000
float findmin(float data[],int n){/*尋覓數據序列中的最小值*/
int index,i;
float min,temp;
temp=data[0];
for(i=1;i<n;i++){
if(data[i]<temp){
temp=data[i];
index=i;
}
}
min=data[index];
return min;
}
float findmax(float data[],int n){/*尋覓數據序列中的最年夜值*/
int index,i;
float max,temp;
temp=data[0];
for(i=1;i<n;i++){
if(data[i]>temp){
temp=data[i];
index=i;
}
}
max=data[index];
return max;
}
void initial(int n,int count[],float low[],float high[],float min,float max){/*初始化區間*/
int i;
for(i=0;i<n;i++){
count[i]=0; //區間能否稀有據存入
low[i]=max; //將區間的左端賦值最年夜值
high[i]=min; //將區間的右端復制最小值
}
}
void dataIn(float m,int count[],float low[],float high[],int n,float data[],float min){/*將數據序列順次放入對應區間*/
int i,location;
for(i=0;i<n;i++){
location=int((data[i]-min)/m)+1; //斷定數據進入哪一個區間:依照等分區間,數據與最小值的差與區間年夜小的比值+1就是區間編號
if(location==n)
location--;
count[location]++; //稀有據存入,計數值加1
if(data[i]<low[location]) //假如數據比左端值小,則作為左端值
low[location]=data[i];
if(data[i]>high[location]) //假如數據比右端值年夜,則作為右端值
high[location]=data[i];
}
}
float findMaxGap(int n,float low[],float high[],int count[]){ /*找出最年夜間隙,全部成績的焦點*/
/*函數解釋*/
/*下面曾經把對應數據放入響應的區間,在之前可以曉得,總共有n-1區間,響應的只要n-2個值,那末就必定有一個區間不會稀有據*/
/*由於最年夜值與最小值曾經分離被設為最小區間的左端值和最年夜區間的右端值,所以中央的n-1區間只要n-2個值*/
/*那末可以想象,最年夜間隙確定不會是在一個區間中,而必定是在空區間的兩頭,
最年夜間隙為空區間左邊相鄰區間的左端值空區間右邊相鄰區間的右端值;有能夠有多個這類情形,找出最年夜就好了*/
int i;
float maxgap,dhigh,temp;
dhigh=high[1];
for(i=2;i<n;i++){
if(count[i]){
temp=low[i]-dhigh;
if(maxgap<temp)
maxgap=temp;
dhigh=high[i];
}
}
return maxgap;
}
int main(){
float data[MAX];
int n,i=0;
float min,max;
float m,maxgap;
float low[MAX],high[MAX];
int count[MAX];
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%f",&data[i]);
min=findmin(data,n);
max=findmax(data,n);
m=(max-min)/(n-1);
initial(n,count,low,high,min,max);
dataIn(m,count,low,high,n,data,min);
maxgap=findMaxGap(n,low,high,count);
printf("%.1f",maxgap);
system("pause");
return 0;
}
感興致的同伙可以測試運轉本文實例以加深懂得。信任本文所述對年夜家C法式算法設計的進修有必定的自創價值。