Working algorithm, but not for big amount of data.