Skip to content

Commit

Permalink
chore: merge sort on An array, IN Place
Browse files Browse the repository at this point in the history
That is: Space complexity is O(1), handy implement is O(n)
STD lib is O(nlogn)
  • Loading branch information
aucker committed Jun 6, 2024
1 parent 0b41037 commit 47290ca
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions daily/June6.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,45 @@ class Solution {
}
return ans;
}

/**
* Sorted Merge LCCI [E]
* 1. from back to begin
* Time: O(n), Space: O(1)
*/
void merge(vector<int>& A, int m, vector<int>& B, int n) {
int k = m + n - 1;
int i = m - 1, j = n - 1;
while (k >= 0 && (i >= 0 || j >= 0)) {
if (i >= 0 && j >= 0 && A[i] >= B[j]) {
A[k] = A[i];
i--;
k--;
} else if (i >= 0 && j >= 0 && A[i] < B[j]) {
A[k] = B[j];
j--;
k--;
} else if (i >= 0 && j < 0) {
A[k] = A[i];
i--;
k--;
} else if (i < 0 && j >= 0) {
A[k] = A[j];
j--;
k--;
}
}
}

/**
* Use STD library of std::sort
* Time: Average: O(nlogn)
* Both works, but this is easy to implement, no much edge case
*/
void mergeSTD(vector<int>& A, int m, vector<int>& B, int n) {
for (int i = 0; i < n; i++) {
A[m + i] = B[i];
}
sort(A.begin(), A.end());
}
};

0 comments on commit 47290ca

Please sign in to comment.