C算法01–常见排序
C算法01–常见排序
C算法01–常见排序
冒泡排序
原理:对一组数据,比较相邻数的大小,将值大的放到后面。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| int a[5] = {11, 222, 33, 44, 55}; int temp; int arrLen = 5; for (int i = 0; i < arrLen - 1; i++) { for (int j = 0; j < arrLen - 1; j++) { if (a[j] > a[j + 1]) { temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } }
for (int i = 0; i < arrLen; i++) { printf("%d ", a[i]); }
|
选择排序
原理:在一组数据中,选出最小的数与第一个位置交换,
然后在剩下的数据中在找出最小的数和第二个位置交换
然后在剩下的数据中在找出最小的数和第三个位置交换
依次类推直到倒数第二个数和最后一个数对比
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| int a[5] = {11, 222, 33, 44, 55}; int minIndex, temp; int arrLen = 5; for (int i = 0; i < arrLen - 1; i++) { minIndex = i; for (int j = i + 1; j < arrLen; j++) { if (a[j] < a[minIndex]) { minIndex = j; } }
temp = a[i]; a[i] = a[minIndex]; a[minIndex] = temp; }
for (int i = 0; i < arrLen; i++) { printf("%d ", a[i]); }
|
斐波那契
1 2 3 4 5 6 7 8 9 10
| int arr[21] = {1, 1}; for (int i = 0; i < 20; i++) { if (i == 0 || i == 1) { printf("1 "); }else{ arr[i] = arr[i - 2] + arr[i - 1]; printf("%d ", arr[i] ); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| int funFoo(n){ if (n == 0 || n == 1) { return 1; } else { return funFoo(n - 1) + funFoo(n - 2); } }
int main() { for (int i = 0; i < 20; i++) { printf("%d ", funFoo(i)); } return 0; }
|