基于单链表的直接插入排序

ゞ 浴缸里的玫瑰 2022-05-28 01:21 292阅读 0赞

问题描述:

用单链表作为待排序数据的存储结构,在其上实现直接插入排序算法。

基本要求:

(1) 待排序数据表采用单链表存储结构;

(2) 设计非降序的直接插入排序算法,要求算法空间复杂度为O(1)。

(3) 输入:待排序表可从文件读入、程序中定义、键盘输入或随机生成;

(4) 输出:待排序记录,已排序记录。

Node.java

LinkList.java

Main.java

  1. package ch01;
  2. public class Node
  3. {
  4. public Object data;
  5. public Node next;
  6. //无参的构造方法
  7. public Node()
  8. {
  9. this(null,null);
  10. }
  11. //有一个参数的构造方法
  12. public Node(Object data)
  13. {
  14. this(data,null);
  15. }
  16. //有两个参数的构造方法
  17. public Node(Object data,Node next)
  18. {
  19. this.data = data;
  20. this.next = next;
  21. }
  22. }

LinkList.java

  1. package ch01;
  2. import ch01.*;
  3. import java.lang.*;
  4. public class LinkList
  5. {
  6. public Node head;
  7. public LinkList()
  8. {
  9. head = new Node(); //头指针
  10. }
  11. //将一个已经存在的带头结点的单链表置成空表
  12. public void clear()
  13. {
  14. head.data = null;
  15. head.next = null;
  16. }
  17. //单链表插入算法
  18. public void insert(int i,Object x)throws Exception
  19. {
  20. Node p = head;
  21. int j=-1;
  22. while(p!=null&&j<i-1)
  23. {
  24. p = p.next;
  25. ++j;
  26. }
  27. if(j>i-1||p==null)
  28. throw new Exception("插入位置不合法!");
  29. Node s = new Node(x);
  30. s.next = p.next;
  31. p.next = s;
  32. }
  33. //直接插入排序算法
  34. public void insertSort(LinkList L)
  35. {
  36. Node p,q,r,u;
  37. p = L.head.next;
  38. L.head.next = null;
  39. while(p!=null)
  40. {
  41. r =L.head;
  42. q=L.head.next;
  43. while(q!=null&&(Integer.valueOf((int)q.data).intValue())<=(Integer.valueOf((int)p.data).intValue()))
  44. {
  45. r = q;
  46. q = q.next;
  47. }
  48. u = p.next;
  49. p.next = r.next;
  50. r.next = p;
  51. p = u;
  52. }
  53. }
  54. public void display()
  55. {
  56. Node node = head.next;
  57. while(node!=null)
  58. {
  59. System.out.print(node.data+" ");
  60. node = node.next;
  61. }
  62. System.out.println();
  63. }
  64. }

Mi

  1. package ch01;
  2. import ch01.*;
  3. import java.util.Scanner;
  4. public class Main
  5. {
  6. public static void main(String []args) throws Exception
  7. {
  8. int n = 10;
  9. Scanner sc = new Scanner(System.in);
  10. LinkList L = new LinkList(); //创建一个空的单链表
  11. for(int i=0;i<n;i++)
  12. {
  13. System.out.print("请输入第"+i+"个数字:");
  14. int t= sc.nextInt();
  15. L.insert(i,t);
  16. }
  17. System.out.println("单链表上的数据为:");
  18. L.display();
  19. System.out.println("排序后的顺序为:");
  20. L.insertSort(L);
  21. L.display();
  22. }
  23. }

2018032712383715

发表评论

表情:
评论列表 (有 0 条评论,292人围观)

还没有评论,来说两句吧...

相关阅读

    相关 插入排序算法

    如果数据存储在一段连续的内存上,比如数组中,插入排序算法的实现相信大家都已经非常熟悉,如果要对一个单链表进行插入排序,将会牵扯到大量指针操作。 同时,如果在实现的过

    相关 归并排序插入排序

    由于最近在学习数据结构和算法,在牛客网 的在线编程题上遇到了对链表的相关排序操作,发现自己对链表这块还是理解不够深入,以前做过对数组进行排序,但链表的操作要比数组复杂一些,毕竟