#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;
}
冒泡排序和选择排序
最新推荐文章于 2025-04-16 17:39:19 发布