博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
基本排序(冒泡,选择,插入,希尔)
阅读量:4957 次
发布时间:2019-06-12

本文共 1414 字,大约阅读时间需要 4 分钟。

#include
#include
#include
void swap(int *a, int i, int j){ int tmp = a[i]; a[i] = a[j]; a[j] = tmp;}void BubbleSort(int *a, int n){ for (int i = 0; i < n - 1; ++i) for (int j = n - 1; j > i; --j) if (a[j] < a[j - 1]) swap(a, j - 1, j);}void SelectSort(int *a, int n){ int k; for (int i = 0; i < n - 1; ++i){ k = i; for (int j = i + 1; j < n; ++j){ if (a[j] < a[k]) k = j; } if (k != i) swap(a, k, i); }}void InsertSort(int *a, int n){ int tmp, j; for (int i = 1; i < n; ++i){ tmp = a[i]; j = i - 1; while (j >= 0 && a[j] > tmp){ a[j + 1] = a[j]; --j; } a[j + 1] = tmp; }}void ShellSort(int *a, int n){ int tmp, j; for (int inc = n / 2; inc > 0; inc /= 2) for (int i = inc; i < n; ++i){ tmp = a[i]; j = i - inc; while (j >= 0 && a[j]>tmp){ a[j + inc] = a[j]; j -= inc; } a[j + inc] = tmp; }}int main(){ srand(time(NULL)); const int cnt = 10; int a[cnt]; for (int i = 0; i < cnt; ++i) a[i] = rand() % 100; ShellSort(a, cnt); for (int i = 0; i < cnt; ++i) printf("%d\t", a[i]); printf("\n");}
View Code

 

转载于:https://www.cnblogs.com/jokoz/p/4691477.html

你可能感兴趣的文章