学归并排序算法的时候,先要了解归并有序数组。
顺便写个有序单链表的归并
/*有序数组的归并*/
function mergeArr(arr1, arr2) {
var result = [],
arr1_index = 0,
arr2_index = 0;
while(arr1_index < arr1.length &&
arr2_index < arr2.length) {
if(arr1[arr1_index] < arr2[arr2_index]) {
result.push(arr1[arr1_index]);
arr1_index++;
} else {
result.push(arr2[arr2_index]);
arr2_index++;
}
}
while(arr1_index < arr1.length) {
result.push(arr1[arr1_index]);
arr1_index++;
}
while(arr2_index < arr2.length) {
result.push(arr2[arr2_index]);
arr2_index++;
}
return result;
}
var arr1 = [1, 2, 4, 20, 30];
var arr2 = [0, 9];
//console.log(mergeArr(arr1, arr2));
/*有序单链表的归并*/
function LinkedList() {
var Node = function (value) {
this.value = value;
this.next = null;
}
var head = null;
var length =0;
this.append = function (value) {
var node = new Node(value);
if(head == null) {
head = node;
length++;
return;
} else {
appendNode(head, node);
}
}
function appendNode(root, node) {
if(root.next == null) {
root.next = node;
} else {
appendNode(root.next, node);
}
length++;
}
this.toString = function () {
var result = [];
var temp = head;
while(temp != null) {
result.push(temp.value);
temp = temp.next;
}
return result.join(" ");
}
this.getHead = function () {
return head;
}
this.getLength = function () {
return length;
}
}
function linkedTest() {
var arr1 = [2, 6, 9, 18, 25];
var arr2 = [0, 10, 30];
var linked_list1 = new LinkedList();
var linked_list2 = new LinkedList();
for(var i=0; i<arr1.length; ++i) {
linked_list1.append(arr1[i]);
}
for(var i=0; i<arr2.length; ++i) {
linked_list2.append(arr2[i]);
}
console.log("linked list1 ", linked_list1.toString());
console.log("linked list2 ", linked_list2.toString());
var merge_list = mergeLinkedList(linked_list1, linked_list2);
console.log(merge_list.toString());
}
/*单链表合并*/
function mergeLinkedList(list1, list2) {
var result_list = new LinkedList(),
list1_node = list1.getHead();
list2_node = list2.getHead();
while(list1_node && list2_node) {
if(list1_node.value < list2_node.value) {
result_list.append(list1_node.value);
list1_node = list1_node.next;
} else {
result_list.append(list2_node.value);
list2_node = list2_node.next;
}
}
while(list1_node) {
result_list.append(list1_node.value);
list1_node = list1_node.next;
}
while(list2_node) {
result_list.append(list2_node.value);
list2_node = list2_node.next;
}
return result_list;
}
linkedTest();