• 基础算法之插入排序


    插入排序是一种最基本的排序方法,时间复杂度为O(n2)。

    其基本思想就是假设A[0, ... j-1]为已经排好序的子数组,通过把A[j]与前面的元素进行比较,将A[j]插入到已经排好顺序的子数组之中。

    用C语言简单实现的插入排序如下:

     1 /* 插入排序的C语言实现, 时间复杂度为O(n2) */
     2 /* a为要排序的数组, LEN为数组的长度 */
     3 void insert_sort(int a[], int LEN)
     4 {
     5     int i, j, key;
     6     for(j=1; j<LEN; j++)
     7     {
     8         key = a[j];
     9         i = j-1;
    10         while(i>0 && a[i]>key)
    11         {
    12             a[i+1] = a[i];
    13             --i;
    14         }
    15         a[i+1] = key;
    16     }
    17 }

    测试代码如下:

     1 #include<stdio.h>
     2 
     3 #define MAXSIZE 10
     4 
     5 /* 插入排序的C语言实现, 时间复杂度为O(n2) */
     6 /* a为要排序的数组, LEN为数组的长度 */
     7 void insert_sort(int a[], int LEN)
     8 {
     9     int i, j, key;
    10     for(j=1; j<LEN; j++)
    11     {
    12         key = a[j];
    13         i = j-1;
    14         while(i>0 && a[i]>key)
    15         {
    16             a[i+1] = a[i];
    17             --i;
    18         }
    19         a[i+1] = key;
    20     }
    21 }
    22 
    23 int main()
    24 {
    25     int a[MAXSIZE];
    26     int i;
    27     printf("Please input the num:
    ");
    28     for(i=0; i<MAXSIZE; i++)
    29     {
    30         scanf("%d",&a[i]);
    31     }
    32     printf("before the sort:
    ");
    33     for(i=0; i<MAXSIZE; i++)
    34     {
    35         printf("%d ", a[i]);
    36     }
    37     printf("
    ");
    38     
    39     insert_sort(a, MAXSIZE);
    40 
    41     printf("after the sort:
    ");
    42     for(i=0; i<MAXSIZE; i++)
    43     {
    44         printf("%d ", a[i]);
    45     }
    46     printf("
    ");
    47 
    48 }
  • 相关阅读:
    java 日期的格式化
    JAVA 线程
    java 异常
    java 内部类
    java 多态
    SpringBoot(12) SpringBoot创建非web应用
    SpringCloud(1) 架构演进和基础知识简介
    SpringBoot(11) SpringBoot自定义拦截器
    SpringBoot(10) Servlet3.0的注解:自定义原生Servlet、自定义原生Listener
    SpringBoot(9) SpringBoot整合Mybaties
  • 原文地址:https://www.cnblogs.com/beyond-Acm/p/4316487.html
Copyright © 2020-2023  润新知