插入排序的一种实现方法,欢迎批评指正!

来源:互联网 发布:ie11不支持js 编辑:程序博客网 时间:2024/05/21 17:07

插入排序和冒泡排序类似,也最简单的排序算法之一,时间复杂度为o(n^2),适用于元素个数较少的数组的排序。如下排序算法没有考虑有相等元素的情况。

#include "stdio.h"

void swap(int *a, int *b)

{

     int temp = *a;

    *a = *b;

    *b = temp;

}

void insert_sort(int a[], int N)

{

    int P = 0, i = 0, temp = 0,j =0;

    for(P = 1; P < N; P++)

    {

        temp = a[P];

         for(j = P; j > 0; j--)//j can  not equal 0 to prevent from j-1 <0

        {

            if(a[j-1] > temp)

            {

                 swap(&a[j-1],&a[j]);

            }

        }

    }

}

void main ()

{

    int a[] = {8,2,9,1,3};

    insert_sort(a,5);

    printf("the sorted array is:%d,%d,%d,%d,%d",*a,*(a+1),*(a+2),*(a+3),*(a+4));

}

0 0