7-27 Bubble method sort (20 points)
Bubble sorting method from small to large sorting from small to large is working like this: two adjacent elements from beginning to end. If the previous elements are greater than the latter elements of their close followers, they exchange them. Through scanning, the last element must be the largest element. Then scan the previous N -1 element in the same way. Based on this type, only two elements need to be processed in the end, and the sort of N numbers is completed.
This question requires that for any given K (<n), the output scan the intermediate result column after the k is completed.
Input format:
Input N and K (1 ≤ K <n≤100) in line 1, and give N integer to be sorted in line 2, and the number is separated by spaces.
output format:
In the line, the bubbling sorting method scan the intermediate result column after the k times. The number is separated by spaces, but there must be no excess space at the end.
Input sample:
6 2
2 3 5 1 6 4
output sample:
2 1 3 4 5 6
Question:It is best to understand bubbling sorting, compare the two numbers of LIAN, large numbers and smaller numbers to change positions. In the first round The third and fourth … sort until the first place. This topic has changed slightly. The input K order needs to pay attention to it. It must be carried out after the K -round, which means that the cycle no longer starts from 0, but starts from K. It should also be noted that there is no space behind the final output number, so take it alone for output, so the loop of the output number is good at N-1 bit.
#include<stdio.h>
int main(void)
{
int N,K,t=0;
int i,j;
int a[100];
scanf("%d %d",&N,&K);
for(i=0;i<N;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<K;i++)
{
for(j=0;j<N-i-1;j++)
{
if(a[j]>a[j+1])
{
t = a[j+1];
a[j+1] = a[j];
a [j] = t;
}
}
}
for(i=0;i<N-1;i++)
{
printf("%d ",a[i]);
}
printf("%d",a[N-1]);
return 0;
}