众所周知编程排序方法众多而且程序的好坏就取决于算法的使用
下面是博主现在会的几种排序方法希望对大家有所帮助。
希尔排序法: /* * @Author: Stylle * @Date: 2020-11-14 15:52:03 * @LastEditors: Stylle * @LastEditTime: 2020-11-14 15:52:16 * @FilePath: \undefinedc:\Users\23999\Desktop\text.c */ #include <stdio.h> void out(int s[]) //数组输出 { int y; for (y = 0; y < 10; y++) { printf(“% d”, s[y]); } } void main() { int s[10] = {10, 9, 8, 6, 7, 5, 4, 3, 2, 1}; int end = 9, start = 0; //开始的下标和结束的下标 int increment = end - start + 1; //长度 int i = 0, temp = 0; do //进行判断长度是否大于1 { increment = increment / 3; // for (i = start + increment; i <= end; i++) //参考插入法可理解 { if (s[i - increment] > s[i]) { temp = s[i]; int j = i - increment; do { s[j + increment] = s[j]; j -= increment; } while (j >= start && s[j] > temp); s[j + increment] = temp; } } } while (increment > 1); out(s); }
冒泡排序:
#include <stdio.h> int main() { int a[10]; int i, n, c; printf(“请输入十个数:\n”); //循环输入模块 for (i = 0; i < 10; i++) scanf(“% d”, &a[i]); //循环判断 for (i = 0; i < 10; i++) { for (n = 0; n < 10; n++) { if (a[i] < a[n]) { c = a[n]; a[n] = a[i]; a[i] = c; } } } //循环输出模块 for (i = 0; i < 10; i++) { printf(“% d “, a[i]); } return 0; }
快速排序法:
#include <stdio.h> void sort(int s[], int left, int right) //进行排序 { if (left < right) //判断取的key两边的数组下标是否符合排序规则 { int i = left, j = right; int key = s[left]; while (i < j) { while (i < j && key <= s[j]) //寻找数组小于key的下标(从右到左) j–; s[i] = s[j]; while (i < j && key >= s[i]) //寻找数组大于key的下标(从左到右) i++; s[j] = s[i]; } s[i] = key; sort(s, left, i - 1); //递归子表1,在key的左边的下标 sort(s, i + 1, right); //递归子表2,在key的右边的下标 } } void out(int s[]) //输出数组 { int i; for (i = 0; i < 10; i++) { printf(“% d”, s[i]); } } void main() { int s[10] = {1, 9, 8, 7, 6, 5, 4, 3, 2, 1}; out(s); printf(“\n”); sort(s, 0, 9); out(s); }