题目描述

已知直接插入排序的部分代码如下,勿改动,请补充实现插入排序函数。要求输出每趟排序结果。
#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 InsertSort(); //InsertSort
};
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.InsertSort();
//L.Display();
return 0;
}

输入

输出

样例输入

12 21 32 2 4 24 21 432 23 9 0

样例输出

12 21 32 2 4 24 21 432 23 9
12 21 32 2 4 24 21 432 23 9
2 12 21 32 4 24 21 432 23 9
2 4 12 21 32 24 21 432 23 9
2 4 12 21 24 32 21 432 23 9
2 4 12 21 21 24 32 432 23 9
2 4 12 21 21 24 32 432 23 9
2 4 12 21 21 23 24 32 432 9
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 InsertSort(){
  21. int j;
  22. for (int i = 2; i <= n; i++) {
  23. r[0] = r[i];
  24. for (j = i - 1; r[0] < r[j]; j--) {
  25. r[j + 1] = r[j];
  26. }
  27. r[j + 1] = r[0];
  28. Display();
  29. }
  30. }
  31. }
  32. public class Main {
  33. public static void main(String[] args) {
  34. Ilist ilist = new Ilist();
  35. Scanner scanner = new Scanner(System.in);
  36. while(true){
  37. int x = scanner.nextInt();
  38. if(x == 0)break;
  39. ilist.InsertR(x);
  40. }
  41. ilist.InsertSort();
  42. }
  43. }