12,常見的資料結構和排序演算法

2021-10-13 17:13:47 字數 3234 閱讀 4996

佇列(queue)

雙向佇列(deque)

常用排序演算法

棧,也被稱為棧堆,是一種容器,支援存入元素、訪問元素和刪除元素。

棧的特點為只允許從容器的一端(棧頂)進行加入資料(push)和輸出資料(pop)的運算。

棧沒有位置的概念,保證可以訪問、刪除的都一定是最後存入的那個元素。這是一種預設的訪問順序。

由於棧資料結構只允許在一段進行操作,因而按照後進先出的原理運作(lifo, last in first out)。

class

stack

(object):

def__init__

(self)

: self.__list =

defpush

(self, item)

:'''add a new item to the top'''

defpop

(self)

:'''pop the item in the top'''

self.__list.pop(

)def

peek

(self)

:'''return the item in the top'''

if self.__list:

return self.__list[-1

]else

:return

none

defis_empty

(self)

:'''decide whether the stack is empty'''

return self.__list ==

defsize

(self)

:'''return the size of the stack'''

return

len(self.__list)

佇列(queue)是一種只允許在一段進行插入操作、另一端進行刪除操作的線性表。

佇列遵循先進先出(fifo,first in first out)的順序。

被允許進行插入操作的一端為隊尾,被允許刪除的那一端為隊首。

假設佇列q = (a1, a2, …, an),那麼a1就是隊頭元素,an則是隊尾元素。

我們總是從隊首開始刪除,在隊尾進行插入。

class

queue

(object):

def__init__

(self)

: self.__list =

defenqueue

(self, item)

:def

dequeue

(self)

:return self.__list.pop(0)

defis_empty

(self)

:return self.__list ==

defsize

(self)

:return

len(self.__list)

deque,全名double-ended queue,是一種具有佇列和棧的性質的資料結構。

雙端佇列中的元素可以從兩端彈出,插入和刪除操作在標的兩端進行。

class

deque

(object):

'''雙端佇列'''

def__init__

(self)

: self.__list =

defadd_front

(self, item)

:'''在頭部新增'''

self.__list.insert(

0, item)

defadd_rear

(self, item)

:'''在尾部新增'''

defpop_front

(self)

:return self.__list.pop(0)

defpop_rear

(self)

:return self.__list.pop(

)def

is_empty

(self)

:return self.__list ==

defsize

(self)

:return

len(self.__list)

def

bubble_sort

(alist)

: n =

len(alist)

for j in

range

(n-1):

for i in

range(0

, n -1)

:if alist[i]

> alist[i+1]

: alist[i]

, alist[i +1]

= alist[i +1]

, alist[i]

def

select_sort

(alist)

: n =

len(alist)

for j in

range

(n-1):

min_index = j

for i in

range

(j+1

, n)

:if alist[min_index]

> alist[i]

: min_index = i

alist[j]

, alist[min_index]

= alist[min_index]

, alist[j]

def

insert_sort

(alist)

: n =

len(alist)

for j in

range(1

, n)

: i = j

while i >0:

if alist[i]

< alist[i-1]

: alist[i]

, alist[i-1]

= alist[i-1]

, alist[i]

i -=

1else

:break

資料結構和演算法 12 之快速排序

學習資料結構和演算法的日常demo 快速排序基本介紹 實現 public class 快速排序 quick a system.out.println arrays.tostring a private static void quick int a 左下標,右下標 private static vo...

資料結構和常見演算法

資料結構中常用的操作的效率表 通用資料結構 查詢 插入 刪除遍歷 陣列o n o n o n 有序陣列 o logn o n o n o n 鍊錶o n o 1 o n 有序鍊錶 o n o n o n o n 二叉樹o logn o logn o logn o n 二叉樹 最壞 o n o n o...

資料結構 幾種常見的排序演算法

下圖是我掌握的一些排序演算法,我將他們做了分類,當然,排序演算法遠不止這些。a 演算法思想 假設第乙個數是有序的,那麼把後面的數拿出來插入到這個有序數的合適位置,假設是公升序 比第乙個數小則向後移動第乙個數,將數插入到第乙個數的前面 插入後有序區間擴大為兩個,依次向後,不斷拿出新的數插入到有序區間,...