Answer the question
In order to leave comments, you need to log in
What is wrong with my array sorting algorithm?
there is an array, dynamic, set randomly using the rand function in the range [0; 2], you need to sort it so that it starts with 1, then there are zeros, and at the end of two, without creating new arrays and without using libraries standard algorithms, well, etc., below is a piece with my sorting algorithm, but for some reason it does not work, only units are sorted to the beginning, and then something goes wrong. Just started learning programming, sorry for the stupid question
int endOfFirstCycle;
int* end = &endOfFirstCycle;
for (int i = 0; i < N; i++) {
int firstElement = i;
for (int currentElement = firstElement; currentElement < N; currentElement++) {
if (array[currentElement] == 1) {
int temp = array[currentElement];
array[currentElement] = array[firstElement];
array[firstElement] = temp;
*end = currentElement + 1;
}
}
}
for (int i = *end; i < N; i++) {
int firstElement = i;
for (int currentElement = firstElement; currentElement < N; currentElement++) {
if (array[currentElement] == 0) {
int temp = array[currentElement];
array[currentElement] = array[firstElement];
array[firstElement] = temp;
}
}
}
Answer the question
In order to leave comments, you need to log in
If the task is exactly like this, then it is solved in two passes. With the first pass you count the number of zeros, ones and twos, with the second pass you fill the array again, based on the counted number.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question