C/C++实现插入排序

 
/**
* @file GM_ISort.h
* @brief 实现插入排序
* @author Don Hao
* @date 2011-8-22 19:46:19
* @version 
* <pre><b>copyright: </b></pre>
* <pre><b>email: </b>[email protected]</pre>
* <pre><b>company: </b>http://blog.csdn.net/donhao</pre>
* <pre><b>All rights reserved.</b></pre>
* <pre><b>modification:</b></pre>
* <pre>Write modifications here.</pre>
*/
#ifndef _GM_ISORT_H
#define _GM_ISORT_H

#ifdef __cplusplus
extern"C"
{
#endif /**< __cplusplus */

    /** 
    * @brief GM_ISort 
    * 
    * Detailed description.
    * @param[in] data 要排序的数据
    * @param[in] size 数据大小
    * @param[in] isDesc 1:降序,否则升序
    */
    void GM_ISort(char* data, int size, int isDesc);
#ifdef __cplusplus
}
#endif /**< __cplusplus */

#endif /**< _GM_ISORT_H */

/**
* @file GM_ISort.c
* @brief 
* @author Don Hao
* @date 2011-8-22 19:46:09
* @version 
* <pre><b>copyright: </b></pre>
* <pre><b>email: </b>[email protected]</pre>
* <pre><b>company: </b>http://blog.csdn.net/donhao</pre>
* <pre><b>All rights reserved.</b></pre>
* <pre><b>modification:</b></pre>
* <pre>Write modifications here.</pre>
*/
#include "GM_ISort.h"

#include <stdlib.h>
#include <stdio.h>

void GM_ISort( char* data, int size, int isDesc )
{
    int i = 0;
    int j = 0;
    int tmp = 0;

    if (NULL == data)
    {
        return;
    }

    if (1 == isDesc)
    {
        for (i = 1; i < size; ++i)
        {
            j = i;
            
            tmp = data[i];

            while((j > 0) && (tmp > data[j - 1]))
            {
                data[j] = data[j - 1];
                --j;
            }

            data[j] = tmp;
        }
    }
    else
    {
        for (i = 1; i < size; ++i)
        {
            j = i;

            tmp = data[i];

            while((j > 0) && (tmp < data[j - 1]))
            {
                data[j] = data[j - 1];
                --j;
            }

            data[j] = tmp;
        }
    }
}
 

int main()
{

    char a[10] = {1, 8, 3, 6, 5, 4, 7, 2, 9, 0};
    char b[10] = {1, 8, 3, 6, 5, 4, 7, 2, 9, 0};

    GM_ISort(a, 10, 1);

    GM_ISort(b, 10, 0);

}

你可能感兴趣的:(C/C++实现插入排序)