快速排序+两个有序链表合并

本文档展示了Java代码实现的快速排序算法以及如何合并两个有序链表。在`Demo`类中演示了快速排序方法,而在`Demo02`类中实现了合并两个链表的功能。
摘要由CSDN通过智能技术生成
package com.wondertek.oes.search.controller.out;

import java.util.Arrays;

/**
 * @Author: lihaojie
 * @Description:
 * @DateTime: 2024/3/18 18:56
 **/
public class Demo {

    public static void main(String[] args) {
        // 数组 用快排
        int[] arr = {6, 1, 2, 7, 9, 3};
        fastSort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));

    }

    private static void fastSort(int[] arr, int low, int high) {
        int left, right, num;
        left = low;
        right = high;
        if (left > high) {
            return;
        }
        num = arr[left];
        while (low != high) {
            for (; high > low; high--) {
                if (arr[high] < num) {
                    arr[low] = arr[high];
                    break;
                }
            }
            for (; low < high; low++) {
                if (arr[low] > num) {
                    arr[high] = arr[low];
                    break;
                }
            }
        }
        arr[low] = num;
        fastSort(arr, left, low - 1);
        fastSort(arr, high + 1, right);
    }

}
package com.wondertek.oes.search.controller.out;

/**
 * @Author: lihaojie
 * @Description:
 * @DateTime: 2024/3/18 19:14
 **/
public class Demo02 {

    public MyNode mergeTwoLists(MyNode l1, MyNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        if (l1.data < l2.data) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }

}

class MyNode {

    int data;
    MyNode next;

    public MyNode(int data) {
        this.data = data;
    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }
}
package com.wondertek.oes.search.controller.out;

/**
 * @Author: lihaojie
 * @Description:
 * @DateTime: 2024/3/18 19:19
 **/
public class Test {

    public static void main(String[] args) {
        // l1
        MyNode l1 = new MyNode(1);
        l1.next = new MyNode(2);
        l1.next.next = new MyNode(4);

        // l2
        MyNode l2 = new MyNode(3);
        l2.next = new MyNode(5);
        l2.next.next = new MyNode(6);

        // 开始合并
        Demo02 solution = new Demo02();
        MyNode mergedList = solution.mergeTwoLists(l1, l2);

        // 打印
        while (mergedList != null) {
            System.out.println(mergedList.data + "");
            mergedList = mergedList.next;
        }

    }

}

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值