1. A non-transitory machine readable medium storing a program which when executed by at least one processor defines structure for a document comprising a plurality of primitive elements, the program comprising sets of instructions for: defining an indirectly sorted first array that stores sorted indices of a second array of difference values, wherein the difference values indicate differences between sorted attribute values of different primitive elements, the primitive elements being defined in terms of the attribute values; using the indirectly sorted first array to generate a plurality of different partition sets at different distance scales for the plurality of primitive elements; from the plurality of partition sets, selecting an optimal partition set based on a set of optimization measures; and grouping the plurality of primitive elements using the optimal partition set in order to associate a subset of the primitive elements as a structured element in the document.