Improved algorithm for pagination generation