选择法排序,冒泡排序,递归排序

#include <stdlib.h>

//选择排序
void SelectSort(int *p, const int length)
{
    if (p == NULL)
    {
        return;
    }

    for (int i = 0; i<length; i++)
    {
        int k = i;                            //记录一轮找到最小值的下标
        for (int j = i+1; j<length; j++)
        {
            if (p[k] > p[j])
            {
                k = j;
            }
        }

        int temp = p[k];
        p[k] = p[i];
        p[i] = temp;
    }
}

//冒泡排序
void BubbleSort(int *p, const int length)
{
    if (p == NULL)
    {
        return;
    }

    for (int i = 0; i<length; i++)
    {
        for (int j = i+1; j<length; j++)
        {
            if (p[i] > p[j])
            {
                int temp = p[j];
                p[j] = p[i];
                p[i] = temp;
            }
        }
    }
}

//递归选择法排序
int RecursiveSelectSort(int *p, int length)
{
    if (p == NULL || 1 == length)
    {
        return 0;
    }

    int k = 0;
    for(int i = 0; i<length; i++)       //找到最小值的下标

    {
        if (p[k] > p[i])
        {
            k = i;
        }
    }

    int temp = p[k];
    p[k] = p[0];
    p[0] = temp;

    p++;                                //找到最小值后,数组向前进一步
    length--;                           //长度当然减小一步
    RecursiveSelectSort(p, length);     //找下一个最小值
    return 1;
}


int main()
{
    int a[7] = {3, 8, 5, 7, 4, 2, 1};
    //SelectSort(a, 7);
    //BubbleSort(a, 7);
    RecursiveSelectSort(a, 7);
    return 1;
}

你可能感兴趣的:(冒泡排序)