Insertion Sort List Leetcode java

题目:

Sort a linked list using insertion sort.

 

题解:

 Insertion Sort就是把一个一个元素往已排好序的list中插入的过程。

 初始时,sorted list是空,把一个元素插入sorted list中。然后,在每一次插入过程中,都是找到最合适位置进行插入。

 因为是链表的插入操作,需要维护pre,cur和next3个指针。

 pre始终指向sorted list的fakehead,cur指向当前需要被插入的元素,next指向下一个需要被插入的元素。

 

 当sortedlist为空以及pre.next所指向的元素比cur指向的元素值要大时,需要把cur元素插入到pre.next所指向元素之前。否则,pre指针后移。最后返回fakehead的next即可。

 

代码如下:

 1  public ListNode insertionSortList(ListNode head) {  
 2          if(head ==  null||head.next ==  null)  
 3              return head;  
 4         ListNode sortedlisthead =  new ListNode(0);  
 5         ListNode cur = head;
 6          while(cur!= null){  
 7             ListNode next = cur.next;  
 8             ListNode pre = sortedlisthead;  
 9              while(pre.next!= null && pre.next.val<cur.val)  
10                 pre = pre.next;  
11             cur.next = pre.next;  
12             pre.next = cur;  
13             cur = next;  
14         }  
15          return sortedlisthead.next;  
16     } 
Java实现插入排序可以使用以下代码: private static void insertionSort(int[] arr) { int len = arr.length; int temp, j; for (int i = 1; i < len; i++) { temp = arr[i]; j = i - 1; while (j >= 0 && arr[j] > temp) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = temp; } System.out.println(Arrays.toString(arr)); } 这段代码使用了插入排序的算法。它首先将数组分为已排序和未排序两部分,然后从未排序部分选择一个元素,将其插入到已排序部分的正确位置。在每次迭代中,将当前元素与已排序部分的元素进行比较,如果当前元素比已排序部分的元素小,则将已排序部分的元素向后移动,然后将当前元素插入到正确的位置。 以上是一种基本的插入排序算法实现,通过比较数组中的相邻元素进行排序。这种算法的时间复杂度为O(n^2),其中n是数组的长度。可以根据实际情况进行性能优化,如使用二分查找来减少比较的次数,或者使用其他排序算法来替代插入排序。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [今日算法解读之Java版插入排序(Insertion Sort)](https://blog.csdn.net/qq_42349895/article/details/117304461)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值