【算法和数据结构】_1_排序算法_1

   三个排序算法:冒泡排序、插入排序、选择排序

/*
    本程序测试各种排序方法
*/

#include <stdio.h>

#define  SORTED 1
#define  NOTSORTED 0

void BubbleSort(int* List,int ListLen);
void BubbleSortF(int* list,int length);
void EchoList(int* List,int ListLen);
void Swap(int* x,int* y);
void InsertSort(int* List,int ListLen);
void SelectSort(int* List,int ListLen);

int main(int argc,char* argv[])
{

    int Test[]={3,4,84,4,3,8,10,12,43};

    //BubbleSort(Test,9);
    BubbleSortF(Test,9);
    //InsertSort(Test,9);
    //SelectSort(Test,9);
    EchoList(Test,9);


    getchar();
    return 0;
}

void EchoList(int* List,int ListLen)
{
    int i;
    for(i=0;i<ListLen;i++)
        printf("%3d  ",List[i]);
}

/*
函数功能:
    冒泡排序
函数原型:
    void BubbleSort(int* List,int ListLen)
函数参数:
    int* List:待排序数组的首地址
    int  ListLen:待排序数组长度
返回值:
    无返回值
异常:
    传递空指针
*/
void BubbleSort(int* List,int ListLen)
{
    int i,
        j;

    for(i=0;i<ListLen-1;i++)
        for(j=0;j<ListLen-i-1;j++)
        {
            if(List[j]<List[j+1])
            {
                 Swap(&List[j],&List[j+1]);
            }
        }
    
}

/*
函数功能:
    改进的冒泡排序
函数原型:
    void BubbleSortF(int* list,int length)
函数参数:
    int* list:待排序数组首地址
    int  length:待排序数组的长度
返回值:
    无
异常:
    传递空指针
*/
void BubbleSortF(int* List,int Length)
{
    int SortFlag;
    int i,
        j;

    SortFlag=NOTSORTED;
    for(i=0;i<Length;i++)
    {
        if(!(SortFlag^SORTED))
            break;
        else
            SortFlag=SORTED;
        for(j=0;j<Length-i-1;j++)
        {   
            if(List[j]<List[j+1])
            {
                 Swap(&List[j],&List[j+1]);
                 SortFlag=NOTSORTED;
            }           
        }
    }
}


/*
函数功能:
    交换两个数字x,y
函数原型:
    void Swap(int* x,int* y)
函数参数:
    待交换的两个数字的地址
返回值:
    无
异常:
    传递空指针
*/
void Swap(int* x,int* y)
{
    *x=*x ^ *y;
    *y=*x ^ *y;
    *x=*y ^ *x;
}


/*
函数功能:
    插入排序
函数原型:
    void InsertSort(int* List,int ListLen)
函数参数:
    int* List:待排序数组首地址
    int* List:待排序数组长度
返回值:
    无
异常:
    传递空指针
*/
void InsertSort(int* List,int ListLen)
{
    int i,
        j,
        temp;

    for(i=1;i<ListLen;i++)
    {
        temp=List[i];
        for(j=i;j>0;j--)
        {
            if(temp<List[j-1])
                List[j]=List[j-1];
            else
            {
                List[j]=temp;
                break;
            }
        }     
    }   
}


/*
函数功能:
    选择排序
函数原型:
    void SelectSort(int* List,int ListLen)
函数参数:
    int* List:待排序序列首地址
    int  ListLen:待排序序列长度
返回值:
    无
异常:
    传递空指针
*/
void SelectSort(int* List,int ListLen)
{
    int i,
        j,
        temp;

    for(i=1;i<ListLen;i++)
    {
        temp=List[i];
        for(j=i;j<ListLen;j++)
        {
            if(temp>List[j])
                Swap(&temp,&List[j]);
        }
        Swap(&temp,&List[i]);
    }
}
原文地址:https://www.cnblogs.com/volcanol/p/3025011.html