資料結構開發 16 選擇排序和插入排序

2022-07-15 06:24:09 字數 2724 閱讀 8351

1.排序的基本概念

2.選擇排序

3.插入排序

4.小結

排序的一般定義:

排序的數學定義:

排序的示例:

問題:排序的穩定性:

穩定性排序示例:

多關鍵字排序:

多關鍵字排序示例:

問題:對於多關鍵字排序,只需要在比較操作時同時考慮多個關鍵字即可!!

演示多關鍵字的比較:

#include #include "object.h"

using namespace std;

using namespace stlib;

struct test : public object

bool operator == (const test& t)

bool operator != (const test& t)

bool operator < (const test& t)

bool operator >= (const test& t)

bool operator > (const test& t)

bool operator <= (const test& t)

};int main()

執行結果為:

(t1 > t2) : 1

(t1 > t3) : 0

排序中的關鍵操作:

排序的審判:

stlib中的排序類設計:

定義stlib中的排序類(sort.h):

#ifndef sort_h

#define sort_h

#include "object.h"

namespace stlib

public:};}

#endif // sort_h

選擇排序的基本思想:

第 i 次選擇排序示例:

實現選擇排序(在sort.h中):

public:

template static void select(t array, int len, bool min2max = true)

}if( min != i )}}

main.cpp測試:

#include #include "sort.h"

using namespace std;

using namespace stlib;

int main()

; sort::select(array, 5);

for(int i=0; i<5; i++)

cout << "~~~" << endl;

sort::select(array, 5, false);

for(int i=0; i<5; i++)

return 0;

}

執行結果為:

123

45~~~543

21

插入排序的基本思想:

第 i 次插入排序示例:

實現插入排序(在sort.h中):

public:

template static void insert(t array, int len, bool min2max = true) // 一邊比較一邊移動

;sort::insert(array, 5);

for(int i=0; i<5; i++)

cout << "~~~" << endl;

sort::insert(array, 5, false);

for(int i=0; i<5; i++)

return 0;

}

執行結果為:

123

45~~~543

21

資料結構和演算法 1 選擇排序 插入排序

一 選擇排序 author eric 從最左邊下標開始,將該下標的元素和它右邊所有元素比較,每一趟遍歷找出最小元素的下標 然後將最小下標的元素和每一趟遍歷開始的最左邊下標的元素互換,即每一趟遍歷都將最小值放在開始遍歷的最左的下標位置 public class selectionsort public...

java 資料結構之選擇排序和插入排序

一 選擇排序 因為氣泡排序,感覺沒必要寫,因為大家應用的基本就是它,所以我今天談談選擇排序,選擇排序屬於較為簡單的排序方法為基本應必須掌握的排序方法。選擇排序 selection sort 是一種簡單直觀的排序演算法。它的工作原理是每一次從待排序的資料元素中選出最小 或最大 的乙個元素,存放在序列的...

資料結構 排序演算法 插入排序 選擇排序

今天我們來總結一下資料結構中各種排序演算法。資料結構排序演算法 part1 直接插入排序 思想 當插入第i i 1 個元素時,前面的array 0 array 1 array i 1 已經排好 序,此時用array i 的排序碼與array i 1 array i 2 的排序碼順序進行比較,找到插入...