自定义元组的排序?

时间:2016-10-17 05:00:28

标签: java python sorting

我正在研究一些常规算法问题,我发现了一个使用以下代码对一组边缘进行排序的java解决方案。每条边都是x位置和高度。

Collections.sort(edges, new Comparator<Edge>() {
    public int compare(Edge a, Edge b) {
        if (a.x != b.x)
            return Integer.compare(a.x, b.x);

        if (a.isStart && b.isStart) {
            return Integer.compare(b.height, a.height);
        }

        if (!a.isStart && !b.isStart) {
            return Integer.compare(a.height, b.height);
        }

        return a.isStart ? -1 : 1;
    }

我想在python中做类似的事情,但我不知道从哪里开始。起初我以为我可以添加一个关键功能,但我不知道在这种情况下我会怎么做。我目前的快速和肮脏的实现远没有效率。我将每个边缘表示为一个列表[x, height],我代表&#34;开始边缘&#34;作为正值和&#34;结束边缘&#34;作为负值(这里不太相关)。

def sort_edges(edges):
    edges.sort(key=lambda x: x[0])
    for i in range(len(edges)-1):
        edge_one = edges[i]
        edge_two = edges[i+1]

        # Continue if edges are not on same x
        if edge_one[0] != edge_two[0]:
            continue
        # Compare height if both are start edges
        if edge_one[1] > 0 and edge_two[1] > 0:
            if edge_two[1] > edge_one[1]:
                temp = edge_one
                edges[i] = edge_two
                edges[i+1] = temp
        # Compare height if both are end edges
        if edge_one[1] < 0 and edge_two[1] < 0:
            if edge_two[1] > edge_one[1]:
                temp = edge_one
                edges[i] = edge_two
                edges[i+1] = temp
        # Start edges come first
        if edge_two[1] > 0 and edge_one[1] < 0:
            temp = edge_one
            edges[i] = edge_two
            edges[i+1] = temp


edges = [[1, 3], [2, 5], [5, -3], [4, -5]]

old = None
while old != edges:
    old = copy(edges)
    sort_edges(edges)

0 个答案:

没有答案