一.基本思路.
1.冒泡排序即是拿第一个数与第二个数作比较,如果第一个数比第二个数大,则两者交换位置(这里我们认为希望得到的是一个升序数列)然后再拿第二个跟第三个数比较,若第二个数大则交换位置,若没有第三个数字大则不交换位置。
2.当一轮比较之后,我们便能得到一个最大的数字,并且它的位置一定是在队列的最后边,这时我们就要注意,下次排序时不再把这个数字加入排序队列当中,能大大提高代码运行效率。
下面便是冒泡排序全过程的动态演示图。
二.代码实现
#include <stdio.h>
#include <windows.h>
extern int test(int arr[], int sz);//函数声明
int main()
{
int arr[] = { 2, 5, 6, 4, 8, 9, 28, 16, 12, 18, 15, 17 };
int sz = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
test(arr,sz);
for (int i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
system("pause");
return 0;
}
static void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
int test(int arr[], int sz)
{
for (int i = 0; i < sz-1; i++)
{
for (int j = 0; j < sz - 1 - i; j++){
if (arr[j]>arr[j + 1]){
swap(&arr[j], &arr[j + 1]);
}
}
}
}
三.问题发现.
如果数组本就是一个有序的数组,那这样循环就会大大提高了代码的时间复杂度。
为解决此问题,那么我们可以定义一个监控的变量,用来监控数组,当进入循环时,一轮循环后,都没有交换任何数值的时候,说明该数列本就是一个有序的数列,我们便不用再执行下去,跳出循环打印结果即可。代码实现如下。
#include <stdio.h>
#include <windows.h>
extern int test(int arr[], int sz);
int main()
{
int arr[] = { 2, 5, 6, 4, 8, 9, 28, 16, 12, 18, 15, 17 };
int sz = sizeof(arr) / sizeof(arr[0]);//计算数组的大小
for (int i = 0; i < sz; i++)//循环打印排序前的数组
{
printf("%d ", arr[i]);
}
printf("\n");
test(arr,sz);
for (int i = 0; i < sz; i++)//打印排序后的数组
{
printf("%d ", arr[i]);
}
system("pause");
return 0;
}
static void swap(int *xp, int *yp)//利用指针交换两个数的值
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
int test(int arr[], int sz)
{
for (int i = 0; i < sz-1; i++)
{
int flag = 1;
for (int j = 0; j < sz - 1 - i; j++){
if (arr[j]>arr[j + 1]){
swap(&arr[j], &arr[j + 1]);
flag = 0;
}
}
if (flag){
break;
}
}
}
四.运行结果.