Skip to content

Instantly share code, notes, and snippets.

public class MergeSort {
static void TopDownMergeSort(int[] a, int[] b, int n) {
CopyArray(a, 0, n, b);
TopDownSplitMerge(b, 0, n, a);
}
static void TopDownSplitMerge(int[] b, int left, int right, int[] a) {
if (right - left < 1)
return;
public class Prime {
public static boolean isPrime(int num) {
if (num > Math.pow(2, 31)) return false;
if (num < 0 || num == 0 || num == 1) return false;
// A not prime num = a * b, a will always smaller or equal to b (vice versa)
// & a and b can't both larger then square root of num(e.g. 36 = 6 * 6 = 4 * 9)
int n = (int)Math.sqrt(num);
for(int i = 2; i <= n ; i++){
if(num % i == 0) return false;
public class ShellSort {
static int gap, i, j, temp;
static void sort(int[] v, int n) {
for (gap = n / 2; gap > 0; gap /= 2) {
for (i = gap; i < n; i++) {
for (j = i - gap; j >= 0 && v[i] < v[j]; j -= gap) {
temp = v[j];
v[j] = v[j + gap];
v[j + gap] = temp;
}
@phc15
phc15 / lis.java
Last active February 17, 2021 01:57
public static int LIS(int[] arr) {
int[] P = new int[arr.length];
int[] M = new int[arr.length + 1];
int L = 0;
int newL = 0;
M[1] = 0;
for (int i = 0; i < arr.length; i++) {
void bfs(Graph graph, int s, boolean[] visited) {
Queue<Integer> queue = new LinkedList<Integer>();
visited[s] = true;
queue.add(s); // enqueue source s
while (!queue.isEmpty()) {
int S = queue.poll(); // dequeue
System.out.println("Visited vertex: " + S);
// check the current vertex's adjacent vertices
for (int n : graph.adj.get(S)) {
@phc15
phc15 / K&R-2-1.c
Last active February 18, 2021 07:26
float fl, fltest, last;
fl = 0.0; // check if the float number is NaN
while(fl == 0.0) {
last = fltest;
fltest += 1.111e+31; // sign bit 1 + exponent 8 bits + mantissa 23 bits
if((fl = (fl + fltest) + (-fltest)) != 0.0) { // 0.0 +∞ + (-∞) == NaN
break;
}
@phc15
phc15 / K&R-1-13.c
Last active February 18, 2021 07:26
#include <stdio.h>
#define MAXLENGTH 10
#define IN 1
#define OUT 0
int main(){
int c, nc, i, max, state;
int wl[maxlength];
void DFSRecursive(Graph g, int s, boolean[] visited) {
System.out.println("Visited vertex: " + s);
visited[s] = true;
for (int n : g.adj.get(s)) {
if (visited[n] == false) {
// visited[n] = true;
DFSRecursive(g, n, visited);
}
@phc15
phc15 / dfs.java
Last active October 1, 2021 06:21
void DFS(Graph graph, int s, boolean[] visited) {
Stack<Integer> stack = new Stack<Integer>();
visited[s] = true;
stack.push(s);
while (!stack.isEmpty()) {
int S = stack.pop();
System.out.println("Visited vertex: " + S);
for (int n : graph.adj.get(S)) {
public class UpdateBits {
public static int update(int n, int m, int i, int j) {
int max = ~0;
int left = max << j+1;
int right = ((1 << i) - 1);
int mask = left | right;
int n_cleared = n & mask;
int m_shifted = m << i;
return n_cleared | m_shifted;