The paper presents a P-wave detection algorithm based on fitting function in the optimal interval. In the algorithm we used quadratic function to fit the P wave by this means of least square method in every interval, which was shifted in local range. Then we found the optimal fitting interval of P wave by comparing the error of fitting. Finally, we obtained the characteristic points of P wave by using the fitting function to fit P wave in the optimal interval. The performance of the algorithm tested using the records of the MIT-BIH database was effective and accurate. The algorithm on the wide range of heart rate variation and small P wave of ECG P-wave detection has good effect. Also it has some capabilities of anti-interference, particularly the false dismissal probability is quite low.