冒泡排序和选择排序

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

#define BUBBLE      1 /* 冒泡 */
#define SELECT      2 /* 选择 */
#define ASCENDING   1 /* 升序 */
#define DESCENDING  2 /* 降序 */

/*
 *冒泡排序和选择排序
 * 参数:str:要排序的数组  str_len:数组长度   select_sort:排序方式(冒泡还是选择排序) sort_way:排序方式(升序或者降序)
 * 返回值:返回排序后的数组首地址
 */
int *bubble_sort(int *str,int str_len,int select_sort,int sort_way)
{
    int i,j,min_max;
    int temp;
    if(select_sort == BUBBLE)
    {
        for(i = 0; i < str_len; i++)
        {
            for(j = 0; j < str_len - i - 1; j++)
            {
                if(sort_way == ASCENDING)
                    if(str[j] > str[j+1])
                    {
                        temp = str[j];
                        str[j] = str[j+1];
                        str[j+1] = temp;
                    }
                if(sort_way == DESCENDING)
                    if(str[j] < str[j+1])
                    {
                        temp = str[j];
                        str[j] = str[j+1];
                        str[j+1] = temp;
                    }
            }
        }
    }

    if(select_sort == SELECT)
    {
        for(i = 0; i < str_len-1; i++)
        {
            min_max = str[i];
            for(j = i+1; j < str_len; j++)
            {
                if(sort_way == ASCENDING)
                    if(str[j] < min_max)
                    {
                        temp = min_max;
                        min_max = str[j];
                        str[j] = temp;
                    }
                if(sort_way == DESCENDING)
                    if(str[j] > min_max)
                    {
                        temp = min_max;
                        min_max = str[j];
                        str[j] = temp;
                    }
            }
            str[i] = min_max;
        }
    }
    return str;
} 

int main(void)
{
    int i;
    int str[10] = {4,7,2,8,24,67,24,67,34,49};
    int *select_result = (int*) malloc(sizeof(str)/sizeof(str[0]));
    select_result = bubble_sort(str,sizeof(str)/sizeof(str[0]),SELECT,ASCENDING);
    printf("选择排序:");
    for(i = 0; i < sizeof(str)/sizeof(str[0]); i++)
    {
        printf("%d\t",select_result[i]);
    }
    putchar(10);

    int *bubble_result = (int*) malloc(sizeof(str)/sizeof(str[0]));
    bubble_result = bubble_sort(str,sizeof(str)/sizeof(str[0]),BUBBLE,DESCENDING);
    printf("冒泡排序:");
    for(i = 0; i < sizeof(str)/sizeof(str[0]); i++)
    {
        printf("%d\t",bubble_result[i]);
    }
    putchar(10);
    free(select_result);
    free(bubble_result);

    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

all of the time

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值