Skip to content

Instantly share code, notes, and snippets.

@ZenulAbidin
Created July 1, 2025 07:23
Show Gist options
  • Save ZenulAbidin/13c999cac6b1955017b767bcda9fe8e1 to your computer and use it in GitHub Desktop.
Save ZenulAbidin/13c999cac6b1955017b767bcda9fe8e1 to your computer and use it in GitHub Desktop.
Merge sort but for pushing zeroes to the end of the array. You can reverse the array to push them towards the beginning, or simply modify the GT function.
// User function template for C++
// consider zeros greater than all other numbers,
// other numbers are equal
bool gt(const int& a, const int& b) {
return a == 0 && b != 0;
}
void swap(int& a, int& b) {
int swap = b;
b = a;
a = swap;
}
// we use mergesort because O(n^2) sort functions take too long
// for this challenge and quicksort is not stable.
// Merges two subarrays of arr[].
// First subarray is arr[left..mid]
// Second subarray is arr[mid+1..right]
void merge(vector<int>& arr, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
// Create temp vectors
vector<int> L(n1), R(n2);
// Copy data to temp vectors L[] and R[]
for (int i = 0; i < n1; ++i) {
L[i] = arr[left + i];
}
for (int j = 0; j < n2; ++j) {
R[j] = arr[mid + 1 + j];
}
int i = 0, j = 0;
int k = left;
// Merge temp vectors back
// into arr[left..right]
while (i < n1 && j < n2) {
// !!! Important !!!
// Do NOT swap the order of these parameters.
// Our gt function does NOT define a strict
// and total order of numbers, so equal numbers
// will appear as REVERSED in the results.
if (!gt(L[i], R[j])) {
arr[k] = L[i];
++i;
}
else {
arr[k] = R[j];
++j;
}
++k;
}
// Copy the remaining elements of L[]
// if there are any
while (i < n1) {
arr[k] = L[i];
++i;
++k;
}
// Copy the remaining elements of R[]
// if there are any
while (j < n2) {
arr[k] = R[j];
++j;
++k;
}
}
// begin is for left index and end is for right index
// of the sub-array of arr to be sorted
void mergesort(vector<int>& arr, int left, int right) {
if (left >= right) {
return;
}
int mid = (right + left) / 2; // === left + (right - left) / 2
mergesort(arr, left, mid);
mergesort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
class Solution {
public:
void pushZerosToEnd(vector<int>& arr) {
int n = arr.size();
return mergesort(arr, 0, n-1);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment