Homework problem: Enter ten numbers randomly and sort by bubble sort. Regarding the bubble sort, you can refer to the following introduction. Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 )
Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
#include<iostream>
using namespace std;
int main() {
//冒泡排序算法
//最常用的、最简单的排序算法
int arr[] = { 5,1,4,2,8 };
//计算数组长度
int length = sizeof(arr)/sizeof(arr[0]);
//1. 比较数组内相邻的元素,如果当下数字比后一个数字大,则交换位置
//2. 当上述步骤做完后,就可以得到第一个最大数(位于数组末尾)
//3. 重复上述步骤,每次的比较数-1,直到不需要再比较为止
//输出排序前的数组
for (int i = 0; i < length; i++)
{
cout << arr[i] << " ";
}
cout << endl;
//排序的总轮数=元素个数-1
for (int i1 = 0; i1 < (length-1); i1++)
{
//每一轮的排序次数=元素个数-排序轮数-1
for (int j = 0; j < (length - i1 - 1); j++)
{
//如果当前数字比下一个数字大,交换这两个数字
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
//输出排序后的数组
for (int i = 0; i < length; i++)
{
cout << arr[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
有两点需要注意:1. 外层循环代表排序轮数,排序总的轮数等于元素个数-1,内层循环表示每一轮的比较次数,等于元素总个数-已经排序的轮数-1。2. 元素交换算法非常基础,要先设定一个temp变量作为数据临时储存的容器,再进行交换。注意,这里的冒泡排序为升序排列,当然也可以进行降序排列。只需要修改交换元素的条件即可。
当要求数组升序排列时,大的数据应该在后,因此当下数字大于后面的数字,自然要换到下标大的位置。当要求数组降序排列时,小的数字应该排列在后,因此当下数字小于后面的数字时,要换到后面的位置。将if条件中的大于号修改为小于号即可。