A Quick Measure of Sortedness
Join the DZone community and get the full member experience.
Join For Freehow do you measure the "sortedness" of a list? there are several ways. in the literature this measure is called the "distance to monotonicity" or the "measure of disorder" depending on who you read. it is still an active area of research when items are presented to the algorithm one at a time. in this article, i consider the simpler case where you can look at all of the items at once.
the kendall distance between two lists is the number of swaps it would take to turn one list into another. so, for [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and [10, 1, 2, 3, 4, 5, 6, 7, 8, 9], it would take nine swaps.
edit distance is another method. we could take the 10, and move it after the 9, in one operation. the edit distance is inversely related to the longest increasing subsequence. in the list [1, 2, 3, 5, 4, 6, 7, 9, 8], the longest increasing subsequence is [1, 2, 3, 5, 6, 7, 9], of length seven, and it is three away from being a sorted list. the longest increasing subsequence can be calculated in o(nlogn) time. a drawback of this method is its large granularity. for a list of ten elements, the measure can only take the distinct values 0 through 9.
here, i propose another measure for sortedness. the procedure is to sum the difference between the position of each element in the sorted list, x, and where it ends up in the unsorted list, f(x). we divide by the square of the length of the list and multiply by two, because this gives us a nice number between 0 and 1. subtracting from 1 makes it range from 0, for completely unsorted, to 1, for completely sorted.
a simple genetic algorithm in python for sorting a list using the above fitness function is presented below.
import random def procreate(a): a = a[:] first = random.randint(0, len(a) - 1) second = random.randint(0, len(a) - 1) a[first], a[second] = a[second], a[first] return a def score(a): diff = 0. for index, element in enumerate(a): diff += abs(index - element) return 1.0 - diff / len(a) ** 2 * 2 def genetic(root, procreatefn, scorefn, generations = 1000, children=6): maxscore = 0. for i in range(generations): print("generation {0}: {1} {2}".format(i, maxscore, root)) maxchild = none for j in range(children): child = procreate(root) score = scorefn(child) print(" child score {0:.2f}: {1}".format(score, child)) if maxscore < score: maxchild = child maxscore = score if maxchild: root = maxchild return root a = [a for a in range(10)] random.shuffle(a) genetic(a, procreate, score)
note that under this metric, the completely reversed list does not have a score of 0.
the spearman's coefficient , mentioned in the comments, might be what you are looking for.
Published at DZone with permission of Steve Hanov, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments