-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[排序] #13
Comments
2 - 384. 打乱数组- 拷贝数组 arr.slice() /**
* @param {number[]} nums
*/
var Solution = function(nums) {
this.origin = nums
};
/**
* Resets the array to its original configuration and return it.
* @return {number[]}
*/
Solution.prototype.reset = function() {
return this.origin
};
/**
* Returns a random shuffling of the array.
* @return {number[]}
*/
Solution.prototype.shuffle = function() {
var arr = this.origin.slice() // copy一个数组
for (let i = 0; i < arr.length; i++) {
var pos = Math.floor(Math.random() * (i + 1)) // 在之前位置的交换
var temp = arr[i]
arr[i] = arr[pos]
arr[pos] = temp
}
return arr
};
/**
* Your Solution object will be instantiated and called as such:
* var obj = new Solution(nums)
* var param_1 = obj.reset()
* var param_2 = obj.shuffle()
*/ |
3 - 希尔排序 |
4 - 148. 排序链表/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var sortList = function(head) {
if (!head || !head.next) return head
var list = []
while (head) {
list.push(head.val)
head = head.next
}
list.sort((a, b) => a - b)
var root = new ListNode(list[0])
var _root = root
for (let i = 1; i < list.length; i++) {
_root.next = new ListNode(list[i])
_root = _root.next
}
return root
}; |
5 - 归并排序
// left, right 都是部分有序
function sort (left = [], right = []) {
var i = 0, j = 0
var result = []
while (i < left.length && j < right.length) {
if (left[i] < right[j]) {
result.push(left[i++])
} else {
result.push(right[j++])
}
}
let temp = []
if (i < left.length) temp = left.slice(i)
if (j < right.length) temp = right.slice(j)
return result.concat(temp)
}
function mergeSort(arr) {
if (arr.length < 2) return arr
var mid = arr.length >> 1
return sort(mergeSort(arr.slice(0, mid)), mergeSort(arr.slice(mid)))
}
mergeSort([7, 6, 5, 4, 3, 2, 1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
1 - 快速排序
The text was updated successfully, but these errors were encountered: