Algorithm / pseudo-code to create paging links?

Well, if you know the current page, it's pretty trivial to just subtract the number by 1, and add it by 1, then check those numbers against the bounds and display the first and last page always, then if they aren't in sequence, add the ellipses.

Or are you asking about getting the total number of pages and determining the current page number...?


There are several other answers already, but I'd like to show you the approach I took to solve it: First, let's check out how Stack Overflow handles normal cases and edge cases. Each of my pages displays 10 results, so to find out what it does for 1 page, find a tag that has less than 11 entries: usability works today. We can see nothing is displayed, which makes sense.

How about 2 pages? Find a tag that has between 11 and 20 entries (emacs works today). We see: "1 2 Next" or "Prev 1 2", depending on which page we're on.

3 pages? "1 2 3 ... 3 Next", "Prev 1 2 3 Next", and "Prev 1 ... 2 3". Interestingly, we can see that Stack Overflow itself doesn't handle this edge case very well: it should display "1 2 ... 3 Next"

4 pages? "1 2 3 ... 4 Next", "Prev 1 2 3 ... 4 Next", "Prev 1 ... 2 3 4 Next" and "Prev 1 ... 3 4"

Finally let's look at the general case, N pages: "1 2 3 ... N Next", "Prev 1 2 3 ... N Next", "Prev 1 ... 2 3 4 ... N Next", "Prev 1 ... 3 4 5 ... N Next", etc.

Let's generalize based on what we've seen: The algorithm seems to have these traits in common:

  • If we're not on the first page, display link to Prev
  • Always display the first page number
  • Always display the current page number
  • Always display the page before this page, and the page after this page.
  • Always display the last page number
  • If we're not on the last page, display link to Next

Let's ignore the edge case of a single page and make a good first attempt at the algorithm: (As has been mentioned, the code to actually print out the links would be more complicated. Imagine each place we place a page number, Prev or Next as a function call that will return the correct URL.)

function printPageLinksFirstTry(num totalPages, num currentPage)
  if ( currentPage > 1 )
    print "Prev"
  print "1"
  print "..."
  print currentPage - 1
  print currentPage
  print currentPage + 1
  print "..."
  print totalPages
  if ( currentPage < totalPages )
    print "Next"
endFunction

This function works ok, but it doesn't take into account whether we're near the first or last page. Looking at the above examples, we only want to display the ... if the current page is two or more away.

function printPageLinksHandleCloseToEnds(num totalPages, num currentPage)
  if ( currentPage > 1 )
    print "Prev"
  print "1"
  if ( currentPage > 2 )
    print "..."
  if ( currentPage > 2 )
    print currentPage - 1
  print currentPage
  if ( currentPage < totalPages - 1 )
    print currentPage + 1
  if ( currentPage < totalPages - 1 )
    print "..."
  print totalPages
  if ( currentPage < totalPages )
    print "Next"
endFunction

As you can see, we have some duplication here. We can go ahead and clean that up for readibility:

function printPageLinksCleanedUp(num totalPages, num currentPage)
  if ( currentPage > 1 )
    print "Prev"
  print "1"
  if ( currentPage > 2 )
    print "..."
    print currentPage - 1
  print currentPage
  if ( currentPage < totalPages - 1 )
    print currentPage + 1
    print "..."
  print totalPages
  if ( currentPage < totalPages )
    print "Next"
endFunction

There are only two problems left. First, we don't print out correctly for one page, and secondly, we'll print out "1" twice if we're on the first or last page. Let's clean those both up in one go:

function printPageLinksFinal(num totalPages, num currentPage)
  if ( totalPages == 1 )
    return

  if ( currentPage > 1 )
    print "Prev"

  print "1"

  if ( currentPage > 2 )
    print "..."
    print currentPage - 1

  if ( currentPage != 1 and currentPage != totalPages )
    print currentPage

  if ( currentPage < totalPages - 1 )
    print currentPage + 1
    print "..."

  print totalPages

  if ( currentPage < totalPages )
    print "Next"

endFunction

Actually, I lied: We have one remaining issue. When you have at least 4 pages and are on the first or last page, you get an extra page in your display. Instead of "1 2 ... 10 Next" you get "1 2 3 ... 10 Next". To match what's going on at Stack Overflow exactly, you'll have to check for this situation:

function printPageLinksFinalReally(num totalPages, num currentPage)
  if ( totalPages == 1 )
    return

  if ( currentPage > 1 )
    print "Prev"

  print "1"

  if ( currentPage > 2 )
    print "..."
    if ( currentPage == totalPages and totalPages > 3 )
      print currentPage - 2
    print currentPage - 1

  if ( currentPage != 1 and currentPage != totalPages )
    print currentPage

  if ( currentPage < totalPages - 1 )
    print currentPage + 1
    if ( currentPage == 1 and totalPages > 3 )
      print currentPage + 2
    print "..."

  print totalPages

  if ( currentPage < totalPages )
    print "Next"

endFunction

I hope this helps!


public void PageLinks(int currentPage, int lastPage) {
    if (currentPage > 2) 
        Add('[1]', '...');
    for(int i=Math.Max(1, currentPage-1); i< Math.Min(currentPage+1, lastPage); i++)
        Add('[i]');
    if (currentPage < lastPage-1)
        Add('...', '[lastpage]');
}

lastPage is calculated as Math.Ceiling(totalRecords/RecordsPerPage).

hmmm. actually, in the case that currentpage is 3, it still shows [1]...[2][3][4]...[xxx] i think the ellipses are superfluous in that case. But that's how it works.

Edit: the preview formats the codeblock correctly, why does it get mangled? sure, its just pseudocode.... but still....


The controls generally show controls for: P1, Pn, Pc (current page), Pc+1, Pc-1. The only time this changes is at either ends of the paging range {Pc < P3 or Pc > (Pn-3)}

  • The first step is to obviously work out the number of pages:

numPages = ceiling(totalRecords / numPerPage)

  • If you've got 4 or less, the drop out at this point, because, by the above rules, the paging is always going to be fixed (P1, P2, Pn-1, Pn), where one will acutally be Pc

  • else, you have three "states"

a. (Pc < P3) - so show P1, P2, P3, Pn, Next If Pc >1, show a 'prev' link before P1.

b. (Pc > Pn - 2), so show Prev, P1, Pn - 2, Pn -1, Pn, show a Next link if Pc < Pn

c. Show Prev, P1, Pc -1, Pc, Pc +1, Pn, Next

Easy as Pie in pseudo code. The loops can get a bit nasty when implemented as you've got to do some iterating in order to generate the links.

Edit: Of course Prev and Next are identical to Pc +/- 1