PTA bubbling sorting c++ version——Shandong University of Science and Technology

Topic:
The bubble sort method that sorts N integers from small to large works like this: compare two adjacent elements from beginning to end, and exchange them if the preceding element is greater than the immediately following element. After one scan, the last element must be the largest element. Then use the same method to scan the first N−1 elements for the second time. By analogy, in the end, only two elements need to be processed to complete the sorting of N numbers.

This question requires that for any given K (<N), output the sequence of intermediate results after scanning the Kth pass.
Input format:

Input N and K (1≤K<N≤100) are given in the first line, and N integers to be sorted are given in the second line, and the numbers are separated by spaces.
Output format:

Output the intermediate result sequence after the K-th pass of the bubble sort method in one line. The numbers are separated by spaces, but there must be no extra spaces at the end.
Input sample:

6 2
2 3 5 1 6 4

Sample output:

2 1 3 4 5 6

topic:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    
    
    int n,k;
    cin>>n>>k;
    int a[n];
    for(int i=0; i<n; i++)
        cin>>a[i];
    for(int i=0; i<k; i++)
        for(int j=0; j<n-i-1; j++)
            if(a[j]>a[j+1])
                swap(a[j],a[j+1]);
    for(int i=0; i<n; i++)
        if(i)
            cout<<' '<<a[i];
        else
            cout<<a[i];
}
更多PTA代码请到我的博客里参考

ps:代码仅供参考,请勿抄袭

Guess you like

Origin blog.csdn.net/scorpion_legend/article/details/109988086