diff --git a/1.bubbleSort.md b/1.bubbleSort.md index 78c3b83..ed2eb42 100644 --- a/1.bubbleSort.md +++ b/1.bubbleSort.md @@ -20,16 +20,27 @@ ![动图演示](res/bubbleSort.gif) +## 3. 算法分析 -## 3. 什么时候最快 +#### 3.1 什么时候最快 当输入的数据已经是正序时(都已经是正序了,我还要你冒泡排序有何用啊)。 +这时只进行一趟排序:元素比较次数为n-1,元素移动为0。 - -## 4. 什么时候最慢 +#### 3.2 什么时候最慢 当输入的数据是反序时(写一个 for 循环反序输出数据不就行了,干嘛要用你冒泡排序呢,我是闲的吗)。 +#### 3.3 时间复杂度 + +设初始文件是反序的,需要进行 n-1 趟排序。每趟排序要进行 n-i 次关键字的比较(1≤i≤n-1),且每次比较都必须移动记录三次来达到交换记录位置。在这种情况下,比较和移动次数均达到最大值: + +比较: C_max = n(n-1)/2 = O(n^2) +移动: M_max = 3n(n-1)/2 = O(n^2) + +冒泡排序的最坏时间复杂度为 O(n^2)。 +综上,因此冒泡排序总的平均时间复杂度为 O(n^2)。 + ## 5. JavaScript 代码实现 @@ -129,3 +140,20 @@ function bubbleSort($arr) return $arr; } ``` +## 10. C 代码实现 +```c +void bubbleSort1(int data[],int n) //n为data长度 +{ + int t; + for(int i=0;i data[j+1]) + { + t = data[j+1]; + data[j+1] = data[j]; + data[j] = t; + } + } + } +} +``` diff --git a/2.selectionSort.md b/2.selectionSort.md index 103830e..4c9e004 100644 --- a/2.selectionSort.md +++ b/2.selectionSort.md @@ -126,3 +126,25 @@ function selectionSort($arr) return $arr; } ``` + +## 8. C 代码实现 + +```c +void selectSort(int *data, int n) +{ + int i, j,t; + int min_index; + for(i = 0; i < n - 1; i ++){ + min_index = i; + for( j = i + 1; j < n; j++){ + if(data[j] < data[min_index]) + min_index = j; + } + if (min_index != i){ + t = data[i]; + data[i] = data[min_index]; + data[min_index] = t; + } + } +} +``` diff --git a/3.insertionSort.md b/3.insertionSort.md index c828cb3..ca5f319 100644 --- a/3.insertionSort.md +++ b/3.insertionSort.md @@ -118,3 +118,27 @@ function insertionSort($arr) return $arr; } ``` + +## 8. C 代码实现 + +``` c +void insert_sort(int data[], int n) +{ + int i,j; + int temp; + for(i=1;i=0)&&(data[j]>temp)) + { + data[j+1]=data[j]; + j--; + } + //存在大于temp的数 + if(j!=i-1) + data[j+1]=temp; + } +} +```