题目描述

已知起泡排序的部分代码如下,勿改动,请补充实现起泡排序函数,要求输出每趟排序结果。
提示:起泡排序时,当某趟排序时,一次交换也未发生,则该趟排序后,即结束。
#include
using namespace std;
const int MaxSize=100;
class List
{
private:
int r[MaxSize+1];
int n;
public:
List(){n=0;} //empty list
void InsertR(int k) //表尾插入
{ r[++n]=k;}
void Display(); //display
void BubbleSort(); //BubbleSort
};
void List::Display()
{
for(int i=1;i<=n;i++)
cout< cout<<”\n”;
}
int main()
{
List L;
while(1)
{
int k;
cin>>k;
if(!k) break;
L.InsertR(k);
}
//L.Display();
L.BubbleSort();
//L.Display();
return 0;
}

输入

输出

样例输入

12 21 32 2 4 24 21 432 23 9 0

样例输出

12 21 2 4 24 21 32 23 9 432
12 2 4 21 21 24 23 9 32 432
2 4 12 21 21 23 9 24 32 432
2 4 12 21 21 9 23 24 32 432
2 4 12 21 9 21 23 24 32 432
2 4 12 9 21 21 23 24 32 432
2 4 9 12 21 21 23 24 32 432
2 4 9 12 21 21 23 24 32 432

提示

来源

提交

  1. import java.util.Scanner;
  2. class Ilist{
  3. int[] r;
  4. int n;
  5. int MaxSize = 100;
  6. public Ilist() {
  7. n = 0;
  8. r = new int[MaxSize];
  9. }
  10. void InsertR(int k){
  11. r[++n] = k;
  12. }
  13. void Display(){
  14. // System.out.print("Data:");
  15. for (int i = 1; i <= n; i++) {
  16. System.out.print(r[i]+" ");
  17. }
  18. System.out.println();
  19. }
  20. void BubbleSort(){
  21. int exchange = n;
  22. while (exchange!=0) {
  23. int bound = exchange;
  24. exchange = 0;
  25. for (int i = 1; i < bound; i++) {
  26. if (r[i] > r[i + 1]) {
  27. int temp = r[i + 1];
  28. r[i + 1] = r[i];
  29. r[i] = temp;
  30. exchange = i;
  31. }
  32. }
  33. Display();
  34. }
  35. }
  36. }
  37. public class Main {
  38. public static void main(String[] args) {
  39. Ilist ilist = new Ilist();
  40. Scanner scanner = new Scanner(System.in);
  41. while(true){
  42. int x = scanner.nextInt();
  43. if(x == 0)break;
  44. ilist.InsertR(x);
  45. }
  46. ilist.BubbleSort();
  47. }
  48. }