冒泡、选择、插入排序总结

#include <stdio.h>
int main()
{
    void bubbleSort(int a[], int n);
    void slectionSort(int a[], int n);
    void insertSort(int a[], int n);
    int a[6] = {5, 2, 1, 0, 6, 3};
    int b[6] = {5, 2, 1, 0, 6, 3};
    int c[6] = {5, 2, 1, 0, 6, 3};
    bubbleSort(a, 6);
    slectionSort(b, 6);
    insertSort(c, 6);

    printf("the result of the bubble sort is:\n");
    for (int i = 0; i < 6; i++)
    {
        printf("%d\n", a[i]);
    }
    printf("\n");

    printf("the result of the selection sort is:\n");
    for (int i = 0; i < 6; i++)
    {
        printf("%d\n", b[i]);
    }

    printf("the result of the selection sort is:\n");
    for (int i = 0; i < 6; i++)
    {
        printf("%d\n", c[i]);
    }

    return 0;
}

void bubbleSort(int a[], int n)
{
    int temp;
    for (int i = 0; i < n - 1; i++)
    {
        for (int j = 0; j < n - i - 1; j++)
        {
            if (a[j + 1] < a[j])
            {
                temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }
    }
}

void slectionSort(int a[], int n)
{
    int minIndex;
    for (int i = 0; i < n - 1; i++)
    {
        minIndex = i;
        for (int j = i + 1; j < n; j++)
        {
            if (a[j] < a[minIndex])
            {
                minIndex = j;
            }
        }
        //交换a[i]和最小的那个数
        int temp;
        temp = a[i];
        a[i] = a[minIndex];
        a[minIndex] = temp;
    }
}

void insertSort(int a[], int n)
{
    int temp, j;
    for (int i = 1; i < n; i++)
    {
        temp = a[i];
        for (j = i; j > 0 && temp < a[j - 1]; j--)
        /*注意:为什么要把 minNow < a[j - 1] 的这个条件写在注释里:
        如果把minNow < a[j - 1] 写在for循环下面的一个if语句里
        j的最后值一定是0,因此就找不到恰好要放进去的那个位置了;
        
        */
        {
            a[j] = a[j - 1];
        }
        a[j] = temp;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值