C/C++ Programming Learning-Week 8 ② Bubble Sort

Topic link

Title description

Bubble sort is a common sorting algorithm. This question requires the bubble sort algorithm to sort a group of positive integers from small to large.

The input is a line of no more than 100 positive integers, which is the number we need to sort. Each positive integer does not exceed 100.

The sorted numbers are output from small to large, separated by spaces, and there is no extra space at the end of the line.

Sample Input

2 1 5 8 21 12

Sample Output

1 2 5 8 12 21

Ideas

To put it simply, bubble sorting is to compare the numbers in the array to small bubbles. The larger the number, the larger the bubble; the smaller the number, the smaller the bubble.

We compare the size of the elements in the array every time, so that the element with a larger value is arranged behind the element with a smaller value, which is like a big bubble floating up. After a traversal, the largest bubble will float up to the end; Then perform a second traversal to make the second largest bubble float to the penultimate position. After n traversals, the array has been sorted from smallest to largest.

sort() is a sorting function. Although the topic of this question is bubble sorting, this does not affect our use of sort (too lazy to write bubble).

The question does not specify how many numbers to enter, so we need to count it ourselves. If there is anything you don’t understand, please ask in the comment area, and I can add as much as possible.

C++ code:

#include<bits/stdc++.h>
using namespace std;
int num[105];
int main()
{
    
    
	int n, i = 0;
	while(cin >> n)
		num[i++] = n;
	sort(num, num + i);
	for(int j = 0; j < i; j++)
		if(j == 0) cout << num[j];
		else cout << " " << num[j];
	cout << endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_44826711/article/details/113079811