演算法 「氣泡排序」程式模擬

2021-07-28 01:27:13 字數 2440 閱讀 3139

文獻:

- data structures and algorithms using c# |michael mcmillan

平台:.net 2.0+

排序最基礎最基本的演算法便是氣泡排序了,bubble sort,最基本的往往最能反映排序的基本思想,基本思路,儘管它做了很多次冗餘的比較。

在.net中通過random,生成隨機數,我們首先建立乙個myarray類,在這個類中內部引用了array物件,提供的功能包括:

static void main(string args)

} }}

每一步發生的交換記錄結果如下,可以看到隨機生成的集合元素(個數設定為10個)位於黃顏色標註的框內。

第1輪比較,共計發生了3次交換,這輪過後,我們能找出這10個元素的最小值為8,並且我們看到在索引位置0處,元素值一共發生了3次改變,分別為24,11,8。

第2輪比較,索引1~9找出最小值為11。

第3輪比較,索引2~9找出最小值12。

第4輪比較,索引3~9找出最小值15。

第5輪比較,索引4~9找出最小值24。

第6輪比較,索引5~9找出最小值26。

第7輪比較,索引6~9找出最小值35。

第8輪比較,索引7~9找出最小值35。

第9輪比較,索引8~9找出最小值39。

最後只剩下乙個元素,沒做任何比較,直接退出。

最終經過9輪比較,共計27次交換,最終完成的集合元素的公升序排列。

大家通過上圖可以看到氣泡排序演算法的基本思路,每經過一輪比較,無序序列中最小值就位。

氣泡排序這些比較中哪些是超過1次的相同的元素比較呢?利用.net提供的linq技術。列印出結果如下圖所示:

從圖中看出,39和42,24和35,都是比較了6次啊!24和35比較了5次啊!由上圖可知,我們看到氣泡排序確實會出現很多次重複比較,要知道這才是排序10個元素啊,這都出現了兩個元素重複比較6次情況!

氣泡排序共計需要n*(n-1)/2次比較,大o意義上為n的平方,才最終將無序序列變為有序。那麼有沒有更優秀的排序方法呢?

請參考模擬「插入排序」演算法!

模擬氣泡排序用到的**,myarray物件

```

public

class myarray

public

void

insert(myelement item)

public

void

clear()

public

override

string

tostring()

return stringbuilder.tostring();

}public

void

fillrandomvalue()

}public

void

printf()

public myelement getat(int index)

//如果a>b,交換;否則直接return

public

static

void

swap(myelement a,myelement b)}}

裡面巢狀的元素類,實現了可以比較icomparable的操作介面,根據元素的val屬性判斷元素的大小關係!

public

class myelement: icomparable

public

intcompareto(object b)

}

linq查重:

```

static

void printfduplicatecompare(listcompares)

into g

where g.count()>1

orderby g.count() descending

select g;

//按val1和val2組合為字典鍵,元素個數為值

var dict = rtnbyval1.todictionary(g => g.key,g=>g.count());

foreach (var item in dict)

和 比較了次\n",item.key.val1,item.key.val2,item.value));}}

用c#描述資料結構4:模擬氣泡排序過程,比較次數分析

拓撲排序程式

拓撲排序 include include define max vertex num 50 define stack size 50 typedef struct arcnodearcnode 鄰接表結點 typedef struct vnodevnode,adjlist max vertex nu...

快速排序程式

快速排序程式 include int findpos int a,int low,int high void quicksort int a,int low,int high intmain 此處可以多試幾組資料 inti quicksort a,0,5 第二個引數表示第乙個元素的下標,第三引數表示...

快速排序程式(windows vs)

sort and count.cpp 定義控制台應用程式的入口點。pragma once include stdafx.h include include include include using namespace std int filelength 100000 int numbers 10...