前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Bubble Sort

Bubble Sort

作者头像
废江_小江
发布2022-09-05 13:19:12
4350
发布2022-09-05 13:19:12
举报
文章被收录于专栏:总栏目

Question

Write a program of the Bubble Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:

代码语言:javascript
复制
BubbleSort(A)
1 for i = 0 to A.length-1
2     for j = A.length-1 downto i+1
3         if A[j] < A[j-1]
4             swap A[j] and A[j-1]

Note that, indices for array elements are based on 0-origin.

Your program should also print the number of swap operations defined in line 4 of the pseudocode.

Input

The first line of the input includes an integer N, the number of elements in the sequence.

In the second line, N elements of the sequence are given separated by spaces characters.

Output

The output consists of 2 lines.

In the first line, please print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.

In the second line, please print the number of swap operations.

Constraints

1 ≤ N ≤ 100

Sample Input 1

5

5 3 2 4 1

Sample Output 1

1 2 3 4 5

8

Sample Input 2

6

5 2 4 6 1 3

Sample Output 2

1 2 3 4 5 6

9

Meaning

实现冒泡排序的过程

Solution

第一层for循环仅仅是为了执行n次循环,然后第二层循环中,从最后一个元素开始,如果比前面的元素小那么就实现交换。这样一层执行完毕,第一个数一定是最小的了。

Coding

代码语言:javascript
复制
#if 1
#include<iostream>
using namespace std;
void BubbleSort(int a[], int n, int &sum) {
	int i, j;
	for ( i = 0; i < n; i++){
		for (j = n - 1; j > i; j--) {
			if (a[j] < a[j - 1])
			{
				swap(a[j], a[j - 1]);
				sum++;
			}
		}
	}
}
void Print(int a[], int n) {
	for (int i = 0; i < n; i++) {
		if (i > 0) cout << " ";
		cout << a[i];
	}
}
int main() {
	int n,sum=0;
	cin >> n;
	int a[105];
	for (int i = 0; i < n; i++)
		cin >> a[i];
	BubbleSort(a, n, sum);
	Print(a, n);
	cout << endl << sum <<endl;
	
}
#endif

废江博客 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权

转载请注明原文链接:Bubble Sort

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-03-28),如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Question
  • Meaning
  • Solution
  • Coding
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档