c冒泡排序(小记)
程序员文章站
2024-03-07 15:49:51
...
#include <stdio.h>
int sumScore(int arr[]);
int highScore(int arr[]);
int lowScore(int arr[]);
float everyScore(int arr[]);
void sortScore(int arr[]);
int length;
int main()
{
int score[10]={67,98,75,63,82,79,81,91,66,84};
//计算数组长度
length = sizeof(score)/sizeof(score[0]);
printf("班级总分为%d\n", sumScore(score));
printf("班级最高分为%d\n", highScore(score));
printf("班级最低分为%d\n", lowScore(score));
printf("班级平均分为%.2f\n", everyScore(score));
printf("班级考试程序将序排序\n");
sortScore(score);
return 0;
}
int sumScore(int arr[])
{
int sum = 0;
for(int i = 0; i < length; i++)
{
sum += arr[i];
}
return sum;
}
int highScore(int arr[])
{
int high = arr[0];
for(int i = 1; i < length; i++)
{
if(arr[i] > high)
high = arr[i];
}
return high;
}
int lowScore(int arr[])
{
int low = arr[0];
for(int i = 1; i < length; i++)
{
if(arr[i] < low)
low = arr[i];
}
return low;
}
float everyScore(int arr[])
{
return 1.0*sumScore(arr)/length;
}
// 冒泡排序
void sortScore(int arr[])
{
for(int i = length-1; i > 0; i--)
{
for(int j = 0; j < i; j++)
{
if(arr[j] > arr[j+1])
{
int temp;
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
for(int i = 0; i < length; i++)
{
if (i != length-1 && i != 0)
{
printf("%d, ", arr[i]);
}
else if(i == length-1)
{
printf("%d]\n", arr[i]);
}
else
{
printf("[%d, ", arr[i]);
}
}
}