4

C 插入排序

 2 years ago
source link: https://blog.ixk.me/post/c-insert-sort
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

C 插入排序

2018-11-20 • Otstar Lin •
本文最后更新于 268 天前,文中所描述的信息可能已发生改变

懒得写开头了(_ _)。゜ z zZ,继续下一个排序算法

1#include <stdio.h>
2#define N 10  //定义要排序的数组长度
3
4//插入排序控制Demo
5//插入排序结果和方式
6//结果:输出排序的数组
7//方式:类似遍历比较
8
9//本例排序从低到高
10
11//插入排序函数
12int* Ins_Sort(int n, int nums[])
13{
14    int i, j, temp;
15    for(i = 1; i < n; i++) //外层循环控制循环轮数,从一开始代表第一个元素默认已经排序
16    {
17        for(j = i - 1; j >= 0; j--) //内层循环控制循环比较的轮数
18        {
19            //在下标 i 左边的元素已经排列,所以只要判断当原 i 的元素已经比第 j 个元素小,即完成此轮排列
20            if(nums[j + 1] >= nums[j])
21            {
22                //完成排列时跳出,防止执行无用的步骤
23                break;
24            }
25            else
26            {
27                //交换数据
28                temp = nums[j + 1];
29                nums[j + 1] = nums[j];
30                nums[j] = temp;
31            }
32        }
33    }
34    //返回数组,其实也可以不用返回,因为操作的就是原数组
35    return nums;
36}
37
38int main(int argc, char const *argv[])
39{
40    //要进行排序的数组,这里就不写循环录入了,直接初始化
41    int nums[N] = {9, 2, 6, 1, 8, 5, 4, 3, 7, 10};
42    int i;
43    //调用函数进行排序
44    int *p = Ins_Sort(N, nums);
45    //循环输出排序好的数组,由小到大
46    for(i = 0; i < N; i++)
47    {
48        printf("%d ", p[i]);
49    }
50    printf("\n");
51    for(i = N - 1; i >= 0; i--)
52    {
53        printf("%d ", p[i]);
54    }
55    return 0;
56}
C 插入排序
Otstar Lin
转载或引用本文时请遵守许可协议,注明出处、不得用于商业用途!

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK