Skip to content

Instantly share code, notes, and snippets.

@mnikn
Last active February 25, 2019 08:37
Show Gist options
  • Save mnikn/b29e6957cbc58cec1fa7e66178f6ebdf to your computer and use it in GitHub Desktop.
Save mnikn/b29e6957cbc58cec1fa7e66178f6ebdf to your computer and use it in GitHub Desktop.
[sort] sort algorithms #algorithm
function bubbleSort(nums){
if (!nums) return;
for(let i = 0;i < nums.length; ++i){
for(let j = 0;j < nums.length-1; ++j) {
if (nums[j] > nums[j+1]) {
let tmp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = tmp;
}
}
}
return nums;
}
function selectionSort(nums) {
if (!nums) return;
for(let i = 0;i < nums.length; ++i){
let min_i = i;
let min_val = nums[i];
for(let j = i;j < nums.length; ++j) {
if (nums[j] < min_val) {
min_val = nums[j];
min_i = j;
}
}
let tmp = nums[i];
nums[i] = nums[min_i];
nums[min_i] = tmp;
}
return nums;
}
function insertion_sort(nums) {
if (!nums) return;
for (let i = 0;i < nums.length;++i) {
let j = i-1;
let value = nums[i];
for (; j >= 0 && nums[j] > value; --j) {
nums[j+1] = nums[j];
}
nums[j+1] = value;
}
return nums;
}
function quickSort(nums, left, right) {
if (!nums || left >= right) return;
let i = left, j = right, target = nums[left];
while(i < j) {
while(i < j && nums[j] >= target) --j;
if(i < j) nums[i++] = nums[j];
while(i < j && nums[i] <= target) ++i;
if(i < j) nums[j--] = nums[i];
}
nums[i] = target;
quickSort(nums, left, i-1);
quickSort(nums, i+1, right);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment