`

归并,选择,冒泡

阅读更多

#!/usr/bin/python
#coding=utf-8
'''
冒泡排序算法
'''

def sort(array):
   i = 0
   len_array = len(array)
   while i < len_array:
      j=i+1
      while j < len_array:
         if array[j] > array[i]:
tmp = array[j]
array[j] = array[i]
array[i] = tmp
         j = j+1
      i = i+1

if __name__ == '__main__':

   array = [2,3,2,45,56,234,132,13,54,0,-1,3]
   sort(array)
   for ii in array:
       print ii,"---",



#!/usr/bin/python
#coding=utf-8

'''

选择排序

'''
def select_sort(array):
   
    length = len(array)
    i = 0
    while i < length:
        tmp = i
        j = i+1

        while j < length:
            if array[j] > array[tmp]:
                tmp = j
            j = j+1

        if  tmp != i :
            tmp_value = array[i]
            array[i] = array[tmp]
            array[tmp] = tmp_value

        i = i+1



if __name__ == '__main__':

    array = [1,23,34,456,3,50,67,-2,4,-67,-575,57570,45,12,2,1,23]
    select_sort(array)

    for i in array:

        print i,'----',
----------------------------------------------------------------------------------
//归并排序:
#!/usr/bin/python
#coding=utf-8


def merger(a,left,right):

    if left == right:

        return
   
    else:

        center = (left+right)/2

        merger(a,left,center)
        merger(a,center+1,right)
        sort(a,left,center,right)


def sort(a,left,center,right):

    tmp_array = []
    tmp_check = 0
    r = right
    l = left
    right_tmp =  center+1
    while left <= center and right_tmp <= right:

        if a[left] >= a[right_tmp]:

            tmp_array.append(a[left])
            left+=1
        else:
            tmp_array.append(a[right_tmp])
            right_tmp+=1
        tmp_check+=1

    while left <= center:

        tmp_array.append(a[left])
        left+=1
        tmp_check+=1
    while right_tmp <= right:

        tmp_array.append(a[right_tmp])
        right_tmp+=1
        tmp_check+=1

    i=0
    while l <= r:
        kk = tmp_array[i]
        a[l]=tmp_array[i]
        i+=1
        l+=1
       
if __name__ == '__main__':

    a=[1,2,4,6,28,40,79,28,1,2,91,92,93,34,52,12]
    merger(a,0,len(a)-1)
    for i in a:
        print i,'***',
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics