Skip to content

Instantly share code, notes, and snippets.

@czheo
czheo / merge_sort.merge_sort.py
Last active November 20, 2016 04:29
merge sort
def merge_sort(a):
if len(a) > 1:
mid = len(a) // 2
left = a[:mid]
right = a[mid:]
merge_sort(left)
merge_sort(right)
merge(left, right, a)
#include <cstddef>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
def quick_sort(numbers,left,right):
if right - left <= 0:
return numbers
tmp = numbers[left]
i = left + 1
j = right
while i < j:
while numbers[j] > tmp and i < j:
def insertion_sort(lst):
i = 1
# invarient:
# We keep the left part of the list sorted:
# [ ..sorted.. i ..unsorted.. ]
while i < len(lst):
# "target" is the item that we want to
# insert back to the left sorted part
# for example:
def selection_sort(lst):
i = 0
n = len(lst)
while i < n:
min_pos = i
for j in range(i, n):
if lst[j] < lst[min_pos]:
min_pos = j
target = lst[min_pos]
import tatsu
from pprint import pprint
import sys
import sys
from tatsu.codegen import ModelRenderer
from tatsu.codegen import CodeGenerator
grammar = """
@@grammar::test
@czheo
czheo / trace.py
Last active April 14, 2018 10:12
a performance tracer for Python
"""
Result:
main->sub1 0.10152816772460938
main->sub2 0.20150494575500488
main 0.31107306480407715
main2->sub1 0.30101609230041504
main2->sub2 0.4036266803741455
main2 0.7056293487548828
"""
l = [509, 838, 924, 650, 604, 793, 564, 651,
697, 649, 747, 787, 701, 605, 644]
def by_dp():
dp = [0] * 5001
i = 0
while i < len(l):
w = 5000
while w >= l[i]:
@czheo
czheo / javascript_tips_1.js
Last active April 14, 2018 11:08
Javascript Tips: 10 Things I Learned from the jQuery Source http://www.youtube.com/watch?v=i_qE1iAmjFg
/* self invoking anon function */
// you may see a wrapper like this
(function (window, document, undefined) {
// code here
})(this, this.document);
/*********** Break Down ************/
// this function invoke itself
(function(){
@czheo
czheo / merge_sort.merge.py
Last active May 11, 2018 06:36
merge sort
def merge(left, right, a):
i = j = k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
# min(left) < min(right)
a[k] = left[i]
i += 1
else:
# min(left) >= min(right)
a[k] = right[j]