python算法

# 二分算法查找 时间复制度log(n)

def binary_search(list,item):

    row = 0

    high = len(list)-1

    while row <= high:
        mid = int((row + high) / 2)

        print('mid'+str(mid))

        guess = list[mid]

        if item == guess:
            return mid

        if item < guess:
            high = mid - 1

        else:
            row = mid + 1

    return None


if __name__ == '__main__':

    res = binary_search([1,3,4,5,7,9],4)

    print(res)
# 选择排序 时间复杂度(O(n*n))

def find_smallest(arr):
    smallest_idx = 0

    smallest = arr[smallest_idx]

    for i in range(len(arr)):

        if arr[i] < smallest:

            smallest_idx = i

            smallest = arr[smallest_idx]


    return  smallest


def section_sort(arr):

    new_arr = []

    for i in range(len(arr)):

        smallest =  find_smallest(arr)

        arr.remove(smallest)

        new_arr.append(smallest)


    print(new_arr)



if __name__ == '__main__':

    section_sort([1,5,3,9])

# 快速排序  时间复杂度:O(nlog(n)) 分而治之

def quick_sort(arr):

    if len(arr) < 2:
        return arr

    else:
        pivot = arr[0]

        less = [i for i in arr[1:] if i <= pivot]

        greater = [i for i in arr[1:] if i> pivot]

        return quick_sort(less) + [pivot] +quick_sort(greater)


if __name__ == '__main__':

    new_arr = quick_sort([1,6,4,3])

    print(new_arr)


#单向链表

#在python当中,所有的变量都是引用,也就是指针; a = 10,表示a 这个引用指向10这块内存;既然a 是引用,也可以去指向其他类型,如
# a= 'hello'

#在其他语言比如c语言当中,int a = 10;这个a 是10这个内存的别名;注意别名不是地址,比如我叫方煜逵,我的别名叫小方,但是我的地址是在员村XXX,你可以到员村XXX这个地址找到我,
#但是你到小方这个地址找到我,显然很扯!所以别名说的还是10这块内存;故这块内存是int类型,就无法在存其他了类型了;当然c语言引入指针类型int *b 来指向10这块内存

class SingleNode(object):

    def __init__(self,item):
        """单链表的结点"""

        # _item存放数据元素
        self.item = item
        # _next是下一个节点的标识
        self.next = None


#单链表的实现
class SingleLinkList(object):

    def __init__(self,head = None):

        self.__head = head

    def is_empty(self):
        """判断链表是否为空"""
        return self.__head == None

    def length(self):
        """链表长度"""
        # cur初始时指向头节点
        cur = self.__head
        count = 0
        # 尾节点指向None,当未到达尾部时
        while cur != None:
            count += 1
            # 将cur后移一个节点
            cur = cur.next
        return count

    def travel(self):
        """遍历链表"""
        cur = self.__head
        while cur != None:
            print(cur.item,end=' ')
            cur = cur.next
        print('')

    # 尾部添加元素
    def append(self,item):
        """尾部添加元素"""

        node = SingleNode(item)

        # 先判断链表是否为空,若是空链表,则将_head指向新节点
        if self.is_empty():
            self.__head = node
        # 若不为空,则找到尾部,将尾节点的next指向新节点
        else:
            cur = self.__head

            while cur.next != None:
                cur = cur.next
            cur.next = node
    #头部添加元素
    def add(self,item):
        """头部添加元素"""
        node = SingleNode(item)
        node.next = self.__head
        self.__head = node

    def insert(self, pos, item):

        if pos <= 0:
            self.add(item)
        elif pos >=  self.length()-1:
            self.append(item)
        else:
            node = SingleNode(item)

            pre_cur = self.__head

            cur_pos = 0

            while cur_pos < pos-1:
                pre_cur = pre_cur.next

                cur_pos += 1

            node.next = pre_cur.next

            pre_cur.next = node

    def search(self, item):
        """链表查找节点是否存在,并返回True或者False"""

        cur = self.__head

        while cur!= None:
            if item == cur.item:
                return True
            else:
                cur = cur.next

        return False

    def remove(self, item):
        """删除节点"""

        cur = self.__head

        pre = None
        
        while cur!= None:
            if item == cur.item:
                # 如果第一个就是删除的节点
                if cur == self.__head:
                    # 将头指针指向头节点的后一个节点
                    self.__head = cur.next
                    cur = self.__head
                else:
                    pre.next = cur.next
                    pre = cur
                    cur = cur.next

            else:

                pre = cur

                cur = cur.next


if __name__ == '__main__':
     l = SingleLinkList()
     l.append(1)
     l.append(2)

     l.append(3)
     l.append(4)


     l.append(5)
     l.append(6)

     l.travel()



#单向循环链表

class SingleNode(object):

    def __init__(self,item):
        """单链表的结点"""

        # _item存放数据元素
        self.item = item
        # _next是下一个节点的标识
        self.next = None


#单链表的实现
class SingleSycLinkList(object):

    def __init__(self,head = None):

        if head:
            self.__head = head
            head.next = self.__head
        else:
            self.__head = None

    def is_empty(self):
        """判断链表是否为空"""
        return self.__head == None

    def length(self):
        """链表长度"""
        # cur初始时指向头节点
        cur = self.__head
        count = 1
        # 尾节点指向None,当未到达尾部时
        while cur.next != self.__head:
            count += 1
            # 将cur后移一个节点
            cur = cur.next
        return count

    def travel(self):
        """遍历链表"""
        if self.is_empty():
            return
        cur = self.__head

        while cur.next != self.__head:
            print(cur.item,end=' ')
            cur = cur.next
        print(cur.item, end=' ')

    # 尾部添加元素
    def append(self,item):
        """尾部添加元素"""

        node = SingleNode(item)

        # 先判断链表是否为空,若是空链表,则将_head指向新节点
        if self.is_empty():
            self.__head = node
            node.next = self.__head
        # 若不为空,则找到尾部,将尾节点的next指向新节点
        else:
            cur = self.__head

            while cur.next != self.__head:
                cur = cur.next
            cur.next = node
            node.next = self.__head
    #头部添加元素
    def add(self,item):
        """头部添加元素"""

        node = SingleNode(item)

        if self.is_empty():
            self.append(item)
            return

        cur = self.__head
        while cur.next != self.__head:
            cur = cur.next

        node.next = self.__head

        cur.next = node

        self.__head = node

    def insert(self, pos, item):

        if pos <= 0:
            self.add(item)
        elif pos >=  self.length()-1:
            self.append(item)
        else:
            node = SingleNode(item)

            pre_cur = self.__head

            cur_pos = 0

            while cur_pos < pos-1:
                pre_cur = pre_cur.next

                cur_pos += 1

            node.next = pre_cur.next

            pre_cur.next = node

    def search(self, item):
        """链表查找节点是否存在,并返回True或者False"""
        if self.is_empty():
            return False

        cur = self.__head

        while cur.next!= self.__head:
            if item == cur.item:
                return True
            else:
                cur = cur.next
        if cur.item == item:
            return True
        return False

    def remove(self, item):
        """删除节点"""

        if self.is_empty():
            return

        cur = self.__head

        pre = None



        while cur.next!= self.__head:
            if item == cur.item:
                # 如果第一个就是删除的节点
                if cur == self.__head:
                    # 将头指针指向头节点的后一个节点
                    real = self.__head
                    while real.next != self.__head:
                        real = real.next

                    real.next = cur.next

                    self.__head = cur.next

                else:
                    pre.next = cur.next
                    pre = cur
                    cur = cur.next

            else:

                pre = cur

                cur = cur.next

        # real = self.__head
        # while real.next != self.__head:
        #     real = real.next
        if item == cur.item:
            pre.next = self.__head





if __name__ == '__main__':
     l = SingleSycLinkList()
     l.append(1)
     # l.append(2)
     # l.append(3)

     # #
     # l.add(0)
     # l.insert(1,2)
     # l.append(4)
     #
     #
     # l.append(5)
     # l.append(6)

     l.remove(1)



     l.travel()

#双向链表

class Node(object):

    def __init__(self,item):
        self.item = item
        self.pre = None
        self.next = None


class DoubleLinkList(object):

    def __init__(self,node = None):
        self.__head = node

    def is_empty(self):
        """链表是否为空"""
        return self.__head == None

    def length(self):
        """链表长度"""
        cur = self.__head
        count = 0
        while cur != None:
            cur = cur.next
            count += 1
        return count

    def travel(self):
        """遍历链表"""
        cur = self.__head
        while cur!= None:
            print(cur.item,end=' ')
            cur = cur.next

        print('')

    def append(self,item):
        """链表尾部添加"""
        node = Node(item)
        if self.is_empty():
            self.__head = node

        else:
            cur = self.__head
            while cur.next != None:
                cur = cur.next
            cur.next = node
            node.pre = cur

    def add(self, item):
        """链表头部添加"""
        node = Node(item)
        if self.is_empty():
            self.__head = node

        else:
            cur = self.__head
            node.next = cur
            cur.pre = node
            self.__head = node

    def insert(self,pos, item):
        """指定位置添加"""
        node = Node(item)
        if pos <=0:
            self.add(item)
        elif pos >= self.length()-1:
            self.append(item)
        else:
            cur = self.__head
            count = 0
            while count < pos:
                cur = cur.next
                count += 1
            cur.pre.next = node

            cur.pre = node

            node = cur.pre

            node.next = cur

    def search(self,item):
        """查找节点是否存在"""
        cur = self.__head
        while cur!=None:
            if cur.item == item:
                return True
            cur = cur.next
        return False

    def remove(self,item):
        """删除节点"""
        if self.is_empty():
            return
        else:
            cur = self.__head

            while cur != None:
                if cur.item == item:
                    node_pre = cur.pre
                    node_next = cur.next
                    #当删除为首结点
                    if cur == self.__head:
                        self.__head = node_next
                        node_next.pre = None
                    # 当删除为尾结点
                    elif node_next == None:
                        cur.pre.next = None

                    else:
                        node_pre.next = node_next
                        node_next.pre = node_pre

                cur = cur.next


if __name__ == '__main__':
    dll = DoubleLinkList()
    dll.append(2)
    dll.append(3)
    dll.append(4)
    dll.append(5)
    dll.add(1)
    dll.insert(2,4)
    dll.remove(1)
    dll.travel()



你可能感兴趣的:(python算法)