C语言实现冒泡排序

c语言 同时被 3 个专栏收录
23 篇文章 0 订阅
12 篇文章 0 订阅
23 篇文章 0 订阅

源代码

Bubble_sort.c

#include <stdio.h>
int main()
{
int a[100], i, j, t, n;
scanf("%d", &n);                // put in a number n, that means you have n numbers to follow
for (i = 1; i <= n; i++)        // Loop through numbers into array A
scanf("%d", &a[i]);

// The core of Bubble Sort
for (i = 1; i <= n-1; i++)      // Sort n numbers, just do n minus 1 times
{
for (j = 1; j <= n-i; j++)  // Compare from the first digit to the last unreturned digit
{
if (a[j] < a[j+1])      // Compare sizes and swap
{
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}

// The output
for (i = 1; i <= n; i++)
printf("%d ", a[i]);
printf("\n");

getchar();
getchar();
return 0;
}



Bubble_sort2.c

#include <stdio.h>
struct student
{
char name[21];
char score;
};  // A structure is created to store the name and score

int main()
{
struct student a[100], t;
int i, j, n;
scanf("%d", &n);            // Put in a number n
for (i = 1; i <= n; i++)    // Loop through n names and scores
scanf("%s %d", a[i].name, &a[i].score);

// Sort by score from highest to lowest
for (i = 1; i <= n-1; i++)
{
for (j = 1; j <= n-i; j++)
{
if (a[j].score < a[j+1].score)  // Compare scores
{
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}

// The output names
for (i = 1; i <= n; i++)
printf("%s\n", a[i].name);

getchar();
getchar();
return 0;
}



总结

• 0
点赞
• 0
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报

08-27 2万+
12-08 276

11-18 163
04-29 1195
08-03 7万+
02-24 72
07-11 3万+
04-05 228

¥2 ¥4 ¥6 ¥10 ¥20

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