效率比较低,时间复杂度应该是O(n*n)吧。
虽然冒泡是一种比较简单的排序,自己写一遍还是有助于深刻理解加记忆。
/*=============================================================================
#
# FileName: BubbleSort.cpp
# Desc: 冒泡排序
#
# Author: yulu
# Email: 187373778@qq.com
#
# Created: 2014-05-01 23:51:00
# Version: 0.0.1
# History:
# 0.0.1 | yulu | 2014-05-01 23:51:00 | initialization
#
=============================================================================*/
#include <stdio.h>
#include <stdlib.h> //rand srand
#include <time.h>
#define SORT_NUM 10
void bubble_sort(int *list,int len)
{
for(int i=0;i<len;i++)
{
for(int j=len-1;j>=i+1;j--)
{
if(list[j]<list[j-1])
{
int temp=list[j];
list[j]=list[j-1];
list[j-1]=temp;
}
}
}
}
void print_array(int *list,int len)
{
for(int i=0;i<len;i++)
{
printf("%3d",list[i]);
if(i!=len-1)
printf(" ");
}
printf("\n");
}
int main(void)
{
int len = SORT_NUM;
int list[len];
srand(time(0));
for (int i = 0; i < len; ++i)
{
list[i] = rand() % 100;
}
print_array(list, len);
bubble_sort(list, len);
print_array(list, len);
return 0;
}