1. 程式人生 > >數據結構算法之求中位數

數據結構算法之求中位數

app num pen 數組元素 組元 整形轉換 end 整形 div

給定兩個有序數組,求其中位數的算法

中位數定義:如果元素個數為奇數,則中位數為數組中間的那個數;如果數組元素個數為偶數,則中位數為中間兩個數的平均數

求解方法一(歸並求解):

def findmidsort(list1,list2):
    num = []
    while list1 and list2:
        if list1[0] > list2[0]:
            num.append(list2[0])
            list2.pop(0)      #除去list2[0]元素後的list2列表
        else:
            num.append(list1[0])
            list1.pop(0)
    if list1 != 0:
        num.extend(list1) 
    if list2 != 0:
        num += list2   #等同以上extend()函數
    if len(num)%2 ==0:
        tem = int(len(num)/2) #需要整形轉換
        res = (num[tem] + num[tem-1])/2
    else:
        res = num[int(len(num)/2)]
    return res

list1 = [1,2,3,6,9,10]
list2 = [1,3,4,11,12,13,14,15,16]
print(findmidsort(list1,list2))

  

數據結構算法之求中位數