#include<stdio.h> #include<stdlib.h> #include<time.h> 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 + 1] < a[j]){ 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 + inc] < a[j]){ 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; SelectSort(a, cnt); for (int i = 0; i < cnt; ++i) printf("%d\t", a[i]); printf("\n"); }
时间: 2024-10-29 04:58:02