implementation of algorithm in C