/** * 快速排序算法 */ void quick_sort (int *s, int l, int r) { if (l < r) { int i = l, j = r, x = s[l]; while (i < j) { while (i < j && s[j] >= x) j--; if (i < j) s[i++] = s[j]; while (i < j && s[i] < x) i++; if (i < j) s[j--] = s[i]; } s[i] = x; quick_sort(s, l, i - 1); quick_sort(s, i + 1, r); } } /** * 冒泡排序 */ void bubble_sort (int *s, int n) { int i = 0, j = 0, temp = 0; for (i = 0; i < n - 1; i++) { for (j = 0; j < n - i - 1; j++) { if (s[j] > s[j + 1]) { temp = s[j]; s[j] = s[j + 1]; s[j + 1] = temp; } } } } /** * 插入排序 */ void insert_sort (int *s, int n) { int i = 0, j = 0, key = 0; for (i = 1; i < n; i++) { j = i - 1; key = s[i]; while (j >= 0 && s[j] > key) { s[j + 1] = s[j]; j--; } s[j + 1] = key; } } /** * 选择排序 */ void section_sort(int *s, int n) { int i = 0, j = 0, min = 0, temp = 0; for (i = 0; i < n; i++) { min = i; for (j = i + 1; j < n; j++) { if (s[j] < s[min]) { min = j; } } if (min != i) { temp = s[i]; s[i] = s[min]; s[min] = temp; } } } static void merge_array (int *s, int first, int mid, int last, int *temp) { int i = first, m = mid; int j = mid + 1, n = last; int k = 0; while (i <= m && j <= n) { if (s[i] <= s[j]) temp[k++] = s[i++]; else temp[k++] = s[j++]; } while (i <= m) temp[k++] = s[i++]; while (j <= n) temp[k++] = s[j++]; for (i = 0; i < k; i++) s[first + i] = temp[i]; } /** * 归并排序 */ void merge_sort (int *s, int first, int last, int *temp) { if (first < last) { int mid = (first + last) / 2; merge_sort(s, first, mid, temp); merge_sort(s, mid + 1, last, temp); merge_array(s, first, mid, last, temp); } }
原文地址:https://www.cnblogs.com/hatsusakana/p/12687164.html
时间: 2024-10-12 22:51:48