标签:
选择排序
#include <stdio.h> /* * 选择排序 * 稳定性:不稳定 * 时间复杂度:O(N^2) **/ void select_sort(int a[], int l, int r) { for (int m_v, m_idx, t, i = l; i < r; ++i) { m_v = a[i]; m_idx = i; for (int j = i + 1; j < r; ++j) { if (m_v > a[j]) { m_v = a[j]; m_idx = j; } } t = a[i]; a[i] = a[m_idx]; a[m_idx] = t; } } int main(void) { int a[100]; int n; scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%d", &a[i]); select_sort(a, 0, n); for (int i = 0; i < n; ++i) printf("%d ", a[i]); return 0; }
冒泡排序
#include <stdio.h> /* * 冒泡排序 * 稳定性:稳定 * 时间复杂度:O(N^2) **/ void bubble_sort(int a[], int l, int r) { for (int i = l; i < r; ++i) { for (int j = l; j < r - i - 1; ++j) { if (a[j] > a[j + 1]) { int tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } } } } int main(void) { int a[100]; int n; scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%d", &a[i]); bubble_sort(a, 0, n); for (int i = 0; i < n; ++i) printf("%d ", a[i]); return 0; }
插入排序
#include <stdio.h> /* * 插入排序 * 稳定性:稳定 * 时间复杂度: O(N^2) **/ void insert_sort(int a[], int l, int r) { for (int tmp, j, i = l + 1; i < r; ++i) { tmp = a[i], j = i - 1; while (j >= l && tmp < a[j]) a[j+1] = a[j--]; a[j+1] = tmp; } } int main(void) { int a[100]; int n; scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%d", &a[i]); insert_sort(a, 0, n); for (int i = 0; i < n; ++i) printf("%d ", a[i]); return 0; }
希尔排序
#include <stdio.h> /* * 希尔排序 * 稳定性:不稳定 * 时间复杂度:O(N*logN) **/ void shell_insert_sort(int a[], int l, int r, int d) { for (int tmp, j, i = l + d; i < r; ++i) { tmp = a[i], j = i - d; while (j >= l && tmp < a[j]) { a[j + d] = a[j]; j -= d; } a[j + d] = tmp; } } void shell_sort(int a[], int l, int r) { int d = (r - l) / 2; while (d >= 1) { shell_insert_sort(a, l, r, d); d /= 2; } } int main(void) { int a[100]; int n; scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%d", &a[i]); shell_sort(a, 0, n); for (int i = 0; i < n; ++i) printf("%d ", a[i]); return 0; }
堆排序
#include <stdio.h> /* * 堆排序 * 稳定性:不稳定 * 时间复杂度:O(N*logN) **/ // big top pile void heap_adjust(int a[], int fa, int n) { int cd = fa * 2 + 1; int tmp = a[fa]; while (cd < n) { if (cd + 1 < n && a[cd] < a[cd + 1]) cd++; if (a[fa] >= a[cd]) break; a[fa] = a[cd]; fa = cd; cd = fa * 2 + 1; a[fa] = tmp; } } void build_heap(int a[], int n) { // ignore leap node for (int i = (n - 1) / 2; i >= 0; --i) { heap_adjust(a, i, n); } } void heap_sort(int a[], int l, int r) { build_heap(a + l, r - l); for (int tmp, i = r - 1; i > l; --i) { tmp = a[i]; a[i] = a[0]; a[0] = tmp; heap_adjust(a + l, 0, i); } } int main(void) { int a[100]; int n; scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%d", &a[i]); heap_sort(a, 0, n); for (int i = 0; i < n; ++i) printf("%d ", a[i]); return 0; }
标签:
原文地址:http://www.cnblogs.com/wenruo/p/5427476.html