您的位置:首页 > 编程语言 > C语言/C++

C语言冒泡排序

2016-03-16 09:32 411 查看
转自:百度知道

冒泡排序每一趟排序把最大的放在最右边。

比如:

87 12 56 45 78

87和12交换:12 87 56 45 78

87和56交换:   56 87 45 78

87和45交换:      45 87 78

87和78交换:         78 87

到此第一趟排序结束,接下来的每一趟排序都是这样。




C qsort函数排序

void qsortTest();
#define NUM 40
void fillarray (double ar[], int n);
void showarray (const double ar[],int n);
int mycomp (const void *p1, const void *p2);//数组排序
int comp (const void *p1, const void *p2);  //比较姓名
struct names {
char first[40];
char last[40];
};

int main(int argc, const char * argv[]) {

struct name b;
b.i = 10;

//mathTest(&b);
qsortTest();

return 0;
}

#pragma mark - 排序
void qsortTest()
{
//qsort() 比较元素大小排序
double vals[NUM];
fillarray(vals, NUM);
puts("Random list: ");
showarray(vals, NUM);
qsort(vals, NUM, sizeof(double), mycomp);
puts("\nSorted list: ");
showarray(vals, NUM);

//比较姓名

}

//数组赋值
void fillarray (double ar[], int n)
{
int index;
for (index = 0; index<n; index++) {
ar[index] = (double) rand()/ ((double) rand()+0.1);
}
}
//读取数组
void showarray (const double ar[],int n)
{
int index;
for (index = 0; index<n; index++) {

printf("%9.4f ",ar[index]);

if (index % 6 == 5)
{
putchar('\n');
}
}

if (index % 6 != 0)
{
putchar('\n');
}
}

int mycomp (const void *p1, const void *p2)
{
/* 需要使用指向double 的指针访问值 */
const double *a1 = (const double *)p1;
const double *a2 = (const double *)p2;

if (*a1 < *a2)
{
return -1;
}
else if (*a1 == *a2)
{
return 0;
}
else
{
return 1;
}
}

int comp (const void *p1, const void *p2)
{
/* 需要使用指向double 的指针访问值 */
const struct names *a1 = (const struct names*)p1;
const struct names *a2 = (const struct names *)p2;
int res;
res = strcmp(a1->last,a2->last);

if (res != 0)
{
return res;
}
else
{
return strcmp(a1->first, a2->first);
}
}


my comp打印结果

Random list: 

   0.0001    1.6475    2.4332    0.0693    0.7268    0.7383 

  24.0357    0.1009   87.1828    5.7361    0.6079    0.6330 

   1.6058    0.1406    0.5933    1.1943    5.5295    2.2426 

   0.8364    2.7127    0.2514    0.9593    8.9635    0.7139 

   0.6249    1.6044    0.8649    2.1577    0.5420   15.0123 

   1.7931    1.6183    1.9973    2.9333   12.8512    1.3034 

   0.3032    1.1406   18.7880    0.9887 

Sorted list: 

   0.0001    0.0693    0.1009    0.1406    0.2514    0.3032 

   0.5420    0.5933    0.6079    0.6249    0.6330    0.7139 

   0.7268    0.7383    0.8364    0.8649    0.9593    0.9887 

   1.1406    1.1943    1.3034    1.6044    1.6058    1.6183 

   1.6475    1.7931    1.9973    2.1577    2.2426    2.4332 

   2.7127    2.9333    5.5295    5.7361    8.9635   12.8512 

  15.0123   18.7880   24.0357   87.1828 

禁用assert 异常断言

#define NDEBUG //禁用assert
#include <assert.h>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: