简体   繁体   中英

How to alphabetically sort 2D array based on an element, without using the built-in sort function? (python)

I've been stuck on this for a while, could some one please help me?

Suppose i have an array:

[[231,cow,234334,2231319,323242],[3,alien,2,2312,3212],[9,box,234,2319,3242]]

Can someone help me create a sort function that sorts the array alphabetically based on the 2nd element of each individual array in the larger array, so that it looks like:

[[3,alien,2,2312,3212],[9,box,234,2319,3242],[231,cow,234334,2231319,323242]]
sort(array, key=lambda x: x[1])

而且,如果您不想使用内置函数,只需创建自己的键控排序函数,然后像上面一样调用它即可。

Mergesort is easy to implement. It's a divide-and-conquer algorithm that breaks the problem into smaller piece (sorting left half, right half, and combining them).

a = [[231,'cow',234334,2231319,323242],[3,'alien',2,2312,3212],[9,'box',234,2319,3242]]

def merge_sort(a):
    # copy the original array so it's unaffected
    b = a[:]
    # if there are 2 or fewer elements, just compare and return in the right order
    if len(b) < 2:
        return b
    elif len(b) == 2:
        x,y = b
        if x[1] <= y[1]:
            return b
        else:
            return [y,x]
    # if there are more than 2, break it to 2 sub-arrays and recursively sort both
    else:
        m = int(len(b)/2)
        p1 = merge_sort(b[:m])
        p2 = merge_sort(b[m:])
        rs = []
        # then combine them by repeatedly popping the smaller one
        while len(p1) > 0 or len(p2) > 0:
            if len(p1) == 0:
                rs.append(p2.pop(0))
            elif len(p2) == 0:
                rs.append(p1.pop(0))
            elif p1[0][1] <= p2[0][1]:
                rs.append(p1.pop(0))
            else:
                rs.append(p2.pop(0))
        return rs

print merge_sort(a)

Here is a simple bubble sort which is one of the easiest sorts to understand (since this looks like homework.) The key, I think, is that the instructor is trying to get you to think about the 2D aspect, which here means you need to look at the second element of the second column in your compare. I have modified the compare for this. I just tested it and you need to put quotes around the elements that are strings.

   def bubblesort( A ):
     for i in range( len( A ) ):
       for k in range( len( A ) - 1, i, -1 ):
         if ( A[k][1] < A[k - 1][1] ):
           swap( A, k, k - 1 )

   def swap( A, x, y ):
     tmp = A[x]
     A[x] = A[y]
     A[y] = tmp

   A=[[231,'cow',234334,2231319,323242],[3,'alien',2,2312,3212],[9,'box',234,2319,3242]]
   print A
   bubblesort(A)
   print A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM