Insertion sort list


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* insertionSortList(ListNode *list)
    {
        ListNode *new_list(NULL), *next(NULL);
        while(list)
        {
            next = list->next;
            new_list = InsertNode(new_list, list);
            list = next;
        }
        return new_list;
    }
private:
    ListNode* InsertNode(ListNode *list, ListNode *node)
    {
        //insert node into a sorted list
        ListNode *pre(NULL), *cur(list);
        while(cur && cur->val < node->val)
        {
            pre = cur;
            cur = cur->next;
        }
        if(pre == NULL){
            node->next = cur;
            return node;
        }
        else{
            node->next = cur;
            pre->next = node;
        }
        return list;
    }
};


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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、付费专栏及课程。

余额充值