C:
void insert(int *B, int size, int val) { if (size == 1) B[0] = val; else { for (int i = 1; i < size; i++) { if (val <= B[i]) { B[i - 1] = val; return; } else { B[i - 1] = B[i]; B[i] = val; } } } } void merge(int *A, int ASize, int m, int *B, int BSize, int n) { if (BSize == 0) return; int point = 0; while (point < m) { if (A[point] > B[0]) { int temp = A[point]; A[point] = B[0]; insert(B, BSize, temp); } point++; } for (int i = m; i < ASize; i++) A[i] = B[i - m]; }
JAVA:
public final void merge(int[] A, int m, int[] B, int n) { if (n == 0) return; int point0 = 0; while (point0 < m) { if (A[point0] > B[0]) { int temp = A[point0]; A[point0] = B[0]; insert(B, temp); } point0++; } for (int i = m; i < n + m; i++) { A[i] = B[i - m]; } } private final void insert(int[] arr, int val) { if (arr.length == 1) arr[0] = val; else { for (int i = 1; i < arr.length; i++) { if (arr[i] >= val) { arr[i - 1] = val; break; } arr[i - 1] = arr[i]; arr[i] = val; } } }
JS:
/** * @param {number[]} A * @param {number} m * @param {number[]} B * @param {number} n * @return {void} Do not return anything, modify A in-place instead. */ var merge = function (A, m, B, n) { if (n == 0) return; let point = 0; while (point < m) { if (A[point] >= B[0]) { let temp = A[point]; A[point] = B[0]; insert(B, temp); } point++; } for (let i = m; i < m + n; i++) A[i] = B[i - m]; }; var insert = function (arr, val) { if (arr.length == 1) return arr[0] = val; for (let i = 1; i < arr.length; i++) { if (val <= arr[i]) arr[i - 1] = val; else { arr[i - 1] = arr[i]; arr[i] = val; } } }