快排和冒泡高质量排序

发表于:2016-2-05 10:31

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:追梦途中    来源:51Testing软件测试网采编

  一、快速排序
  (1)排列整数:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int com_int(const void *elem1, const void *elem2 )
{
return *(int *)elem1 - *(int *)elem2;
}
int main()
{
int arr[] = { 1, 3, 5, 7, 2, 4, 6, 8 };
int i = 0;
qsort(arr,
sizeof(arr) / sizeof(arr[0]),
sizeof(arr[0]), com_int);
for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
{
printf("%d ", arr[i]);
}
printf("\n");
system("pause");
return 0;
}
  运行结果:
  1 2 3 4 5 6 7 8
  (2)排列多个字符串:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int com_str(const void *elem1, const void *elem2)
{
return strcmp((char *)*(int *)elem1,
(char *)*(int *)elem2);
}
int main()
{
char *arr[] = {"bbbb","aaaa","dddd","cccc"};
int i = 0;
qsort(arr,
sizeof(arr) / sizeof(arr[0]),
sizeof(arr[0]), com_str);
for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
{
printf("%s ", arr[i]);
}
printf("\n");
system("pause");
return 0;
}
  运行结果:
  aaaa bbbb cccc dddd
  二、冒泡排字符串
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void bubble_sort(char*str[], int sz)
{
int i = 0;
int j = 0;
for (i = 0; i < sz - 1; i++)
{
for (j = 0; j < sz - 1 - i; j++)
{
if (strcmp(str[j], str[j + 1])>0)
{
char*tmp = NULL;
tmp = str[j];
str[j] = str[j + 1];
str[j + 1] = tmp;
}
}
}
}
int main()
{
char*str[] = { "hello", "world", "to", "bit", "welcome" };//指针数组
int i = 0;
bubble_sort(str, sizeof(str) / sizeof(str[0]));
for (i = 0; i < sizeof(str) / sizeof(str[0]); i++)
{
printf("%s ", str[i]);
}
printf("\n");
system("pause");
return 0;
}
  结果:
  bit hello to welcome world
21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号