Number of data exchanges in bubble sort

[Description of Problem]
The principle of the bubble sorting algorithm is as follows:
compare adjacent elements. If the first one is bigger than the second one, swap them both.
Do the same for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. At this point, the last element should be the largest number.
Repeat the above steps for all elements except the last one.
Continue to repeat the above steps for fewer and fewer elements each time until there are no pairs of numbers to compare.
Now I want to figure out how many data exchanges have been performed during the sorting process from small to large.
[Input form]
The first line of input data is a positive integer T, indicating that there are T sets of test data.
Next T lines, the first integer N in each line, then N integers, unordered. 0 <N <= 100
[Output form] The
output is T lines in total.
An integer in each line represents the number of exchanges in the bubble sort of the data in this line from small to large.
[Sample input]
3
5 1 2 3 4 5
4 5 3 7 1
2 2 1

[Sample output]
0
4
Analysis:
1. The principle of bubble sorting: Suppose there are n data that need to be sorted. We need to use the loop here to take the arrangement from small to large as an example.
① Find the largest number among the n data (the method is Compare two adjacent numbers. If the previous number is larger than the latter, exchange the two numbers.) Use this method to put the largest number in the last position and then n-1.
②This method can be used every time. Find a maximum value and put it in the back because the last cycle has become an ordered sequence, so the outer loop can be n-1 times.
2. For this problem, only need to use a counter to count the last printout when exchanging data. can

#include <iostream>

using namespace std;

int main()
{
    int T;
    cin>>T;
    while(T--)//T组数据
    {
        int N,t,sum=0;//计数器
        cin>>N;
        int data[N];
        for(int i=0;i<N;i++)
        {
            cin>>data[i];//录入数据
        }
        for(int i=0;i<N-1;i++)//外层循环 循环n-1次
        {
            for(int j=0;j+i<N-1;j++)//内层循环 找到最大的
            {
                if(data[j]>data[j+1])
                {
                    t=data[j];
                    data[j]=data[j+1];
                    data[j+1]=t;
                    sum++;//每次交换计数器加一


                }
            }
        }
//        for(int i=0;i<N;i++)
//            cout<<data[i]<<" ";
//        cout<<endl;
        cout<<sum<<endl;//最后输出计数器的值
    }
}

Below is a little white. If there is an inappropriate place, please correct me.

Published 31 original articles · won praise 8 · views 2155

Guess you like

Origin blog.csdn.net/weixin_44034024/article/details/105240378