冒泡排序
冒泡排序的算法复杂度为O(n2),其原理就是将相邻的两个数进行比较,如果第一个数比第二个数大,则交换两个数的位置,否者不交换。通过一轮交换,最大的数肯定被排到了数组的最后一位,所以数组的最后一位便是整个数组最大的数,下一轮遍历的时候便不考虑最后一位数据,依次循环到最后,数组被排序完成。
代码:
#include<iostream>
#include<string>
using namespace std;
void BubbleSort(int* buf, int length);
int main()
{
int buff[7] = { 5, 2, 1, 4, 9, 6, 0 };
for (int i = 0; i < 7; i++)
cout << buff[i] ;
cout << endl;
BubbleSort(buff, 7);
for (int i = 0; i < 7; i++)
cout << buff[i];
cout << endl;
return 0;
}
void BubbleSort(int* buf, int length)
{
int temp=0;
while (length > 0)
{
///
for (int i = 0; i < length - 1; i++)
{
temp = buf[i];
if (temp>buf[i + 1])
{
buf[i] = buf[i + 1];
buf[i + 1] = temp;
}
}
/ 这里是将一种长度的进行冒泡,然后将最大的值传递到最后一位
length--;
}
}
可以看到,while循环里的for循环便是一轮遍历,不断交换是的最大的数移动到数组的最后一位。然后数组的长度减少1,再次进行下一轮遍历,再将最大的数放到数组的倒数第二位,长度再减去1,。。。。直到跳出while循环,排序完成。
效果: