import java.util.Arrays;
class ListNode {
int value;
ListNode next;
public ListNode(int value) {
this.value = value;
}
}
public class MergeSort {
/**
* 数组归并排序
*/
public static void mergeTwoArray(int[] array, int low, int mid, int high) {
int[] temp = new int[array.length];
int k = 0;
int i = low;
int j = mid + 1;
while (i <= mid && j <= high) {
if (array[i] < array[j]) {
temp[k++] = array[i++];
} else {
temp[k++] = array[j++];
}
}
while (i <= mid) {
temp[k++] = array[i++];
}
while (j <= high) {
temp[k++] = array[j++];
}
System.arraycopy(temp, 0, array, low, k);
}
public static void mergeSort(int[] array, int low, int high) {
if (low < high) {
int mid = (low + high) / 2;
mergeSort(array, low, mid);
mergeSort(array, mid + 1, high);
mergeTwoArray(array, low, mid, high);
}
}
/**
* 单链表归并排序
*/
public static ListNode mergeTwoList(ListNode list1, ListNode list2) {
ListNode dummyHead = new ListNode(0);
ListNode tail = dummyHead;
while (list1 != null && list2 != null) {
if (list1.value < list2.value) {
tail.next = list1;
tail = list1;
list1 = list1.next;
} else {
tail.next = list2;
tail = list2;
list2 = list2.next;
}
}
while (list1 != null) {
tail.next = list1;
tail = list1;
list1 = list1.next;
}
while (list2 != null) {
tail.next = list2;
tail = list2;
list2 = list2.next;
}
tail.next = null;
return dummyHead.next;
}
public static ListNode mergeSortForList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode rightHead = slow.next;
slow.next = null;
ListNode list1 = mergeSortForList(head);
ListNode list2 = mergeSortForList(rightHead);
return mergeTwoList(list1, list2);
}
public static ListNode createList(int[] array) {
ListNode dummyHead = new ListNode(0);
ListNode tail = dummyHead;
for (int d : array) {
ListNode newNode = new ListNode(d);
tail.next = newNode;
tail = newNode;
}
return dummyHead.next;
}
public static void printList(ListNode head) {
ListNode p = head;
while (p != null) {
System.out.print(p.value + ", ");
p = p.next;
}
System.out.println();
}
public static void main(String[] args) {
int[] array = {12, 3, 11, 45, 23, 9, 1, 0, 666, 55, 78, 2, 77, 128, 1024};
int[] arrayCopy = {12, 3, 11, 45, 23, 9, 1, 0, 666, 55, 78, 2, 77, 128, 1024};
ListNode head = createList(array);
ListNode sortedHead = mergeSortForList(head);
System.out.print("链表排序 结果:[");
printList(sortedHead);
mergeSort(array, 0, array.length - 1);
System.out.println("数组排序 结果:" + Arrays.toString(array));
Arrays.sort(arrayCopy);
System.out.println("Arrays.sort结果:" + Arrays.toString(arrayCopy));
}
}
归并排序
最新推荐文章于 2023-09-03 20:36:33 发布