Bubble Sort
- 对数组中的各数据,依次比较相邻的两个元素的大小。
- 如果前面的数据大于后面的数据,就交换这两个数据。经过第一轮的多次比较排序后,便
可把最小的数据排好。 - 然后 ,再用同样的方法把剩下的数据逐个进行比较,最后便可按照从小到大的顺序排好数
组中各数据的顺序
#include <iostream>
#include <cstdlib>
#include <ctime>
const int SIZE = 10;
int main()
{
void BubbleSort(int *a, int len);
int array[SIZE], i;
srand(time(NULL));
for (i=0;i<SIZE;i++)
{
array[i] = rand()/1000+10;
}
std::cout << "排序前的数组为:" << std::endl;
for (i=0;i<SIZE;i++)
{
std::cout << array[i] << " ";
}
std::cout << std::endl;
BubbleSort(array, SIZE);
std::cout << "排序后的数组为:" << std::endl;
for (i=0;i<SIZE;i++)
{
std::cout << array[i] << " ";
}
std::cout << std::endl;
return 0;
}
void BubbleSort(int *a, int len)
{
int i, j, k, temp;
for (i=0;i<len-1;i++)
{
for (j=len-1;j>i;j--)
{
if (a[j-1]>a[j])
{
temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}
std::cout << "第" << i << "步排序结果:";
for (k=0;k<len;k++)
{
std::cout << a[k] << " ";
}
std::cout << std::endl;
}
}
import numpy as np
def Bubble_Sort(value):
"""
Bubble Sort
:param value: random array
:return: Sort array
"""
for i in range(len(value)-1):
for j in range(len(value)-1):
if (value[j] > value[j+1]):
value[j], value[j+1] = value[j+1], value[j]
print("Bubble Sort: ")
print(value)
def main():
list = np.random.randint(100, size=10)
print("排序前的数组为: ")
print(list)
Bubble_Sort(list)
if __name__ == "__main__":
main()