08 Go語言高階學習 排序 鍊錶 二叉樹

2021-09-24 13:33:12 字數 1650 閱讀 5260

1. 排序

1) 氣泡排序的4種寫法:

package main

import

("fmt"

)//用於計數排序中訪問了多少次序列

var cnt int=0

//1.最原始的氣泡排序

func

buble_sort

(a [

]int)}

cnt++

//每完成一次內迴圈就訪問了一次序列}}

//2.增加標誌判斷是否發生交換,如果沒有發生交換,表明序列有序,結束比較,直接退出

func

flag_sort

(a [

]int)}

cnt++

//每完成一次內迴圈就訪問了一次序列

if flag }}

//3.除了標誌位以外,記錄最後一次發生交換的下標,更能減少不必要的比較

func

better_sort

(a [

]int)}

cnt++

if flag

k = n//最後一次交換的位置給k,減少比較的次數}}

//4.雞尾酒氣泡排序--先從低到高,再從高到低--分為兩大步驟,結合標誌判斷

func

cocktail_sort

(a [

]int)}

cnt++

right--

if flag

for i :=right; i > left; i--

} cnt++

left++

if flag }}

func

main()

buble_sort

(b[:])

fmt.

println

(b,cnt)

d :=

intflag_sort

(d) fmt.

println

(d,cnt)

e :=

intbetter_sort

(e) fmt.

println

(e,cnt)

c :=

intcocktail_sort

(c) fmt.

println

(c,cnt)

}

執行結果如下圖:

2. 鍊錶

type student struct

2) 雙鏈表定義:如果有兩個指標分別指向前乙個節點和後乙個節點,我們叫做雙鏈表,比如:

type student struct

3. 二叉樹

1) 二叉樹定義:如果每個節點有兩個指標分別用來指向左子樹和右子樹,我們把這樣的結構叫做二叉樹。比如:

type student struct

注意:make 用來建立map、slice、channel ; new用來建立值類

二叉排序樹鍊錶實現

二叉排序數的 遞迴 定義 1 若左子樹非空,則左子樹所有節點的值均小於它的根節點 2 若右子樹非空,則右子樹所有節點的值均大於於它的根節點 3 左右子樹也分別為二叉排序樹。如圖 鍊錶實現 比較簡單 include include typedef struct node node void init ...

C語言實現二叉樹(二叉鍊錶)

方法二 根據所給的字串序列建立 其他方法 define elemtype char typedef struct bintreenode bintreenode typedef struct bintree void initbintree bintree bt,elemtype ref 1按照先序...

go語言結構體實現簡單的鍊錶與二叉樹

1.鍊錶 1 頭部插入法 實現鍊錶結構 package main import fmt math rand type student struct func main stu.next tail tail stu 遍歷移動鍊錶元素 trans tail struct 是值型別,要想改變其值,只有傳遞...