Skip to content

Commit

Permalink
Merge pull request sherigar#182 from avishka45/main
Browse files Browse the repository at this point in the history
program for problem - Sort an array of 0s, 1s and 2s
Rate limit · GitHub

Access has been restricted

You have triggered a rate limit.

Please wait a few minutes before you try again;
in some cases this may take up to an hour.

sherigar authored Oct 17, 2023
2 parents 0f30dfa + c21cabe commit c172223
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions c++/Sort_0_1_2.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include <iostream>

void sortColors(int arr[], int size) {
int low = 0; // Pointer for 0
int high = size - 1; // Pointer for 2
int current = 0; // Pointer for iterating through the array

while (current <= high) {
if (arr[current] == 0) {
std::swap(arr[current], arr[low]);
current++;
low++;
} else if (arr[current] == 2) {
std::swap(arr[current], arr[high]);
high--;
} else {
current++;
}
}
}

void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}

int main() {
int arr[] = {0, 1, 2, 0, 1, 2, 1, 0, 2};
int size = sizeof(arr) / sizeof(arr[0]);

std::cout << "Original array: ";
printArray(arr, size);

sortColors(arr, size);

std::cout << "Sorted array: ";
printArray(arr, size);

return 0;
}

0 comments on commit c172223

Please sign in to comment.