Estou acompanhando um tutorial em vídeo de C++ online. Em dado momento, tentei escrever código para o problema descrito no título desta questão. Mais tarde, o instrutor mostrou sua abordagem e não consegui decidir qual código é melhor, pois ambos dão o mesmo resultado.
#include <iostream>
using namespace std;
// Array construction
struct Array {
int A[10];
int size;
int length;
};
void Swap(int *des, int *source) {
int temp = *des;
*des = *source;
*source = temp;
}
Implementação do instrutor:
void Rearrange(Array* arr)
{
int i = 0;
int j = arr->length - 1;
while (i < j) {
while (arr->A[i] < 0)
i++;
while (arr->A[i] >= 0)
j--;
if (i < j)
Swap(&arr->A[i], &arr->A[j]);
}
}
Minha implementação:
void ArrangeNegativeOnLeft(Array *arr) {
int i = 0;
int j = arr->length - 1;
while (i < j) {
if (arr->A[i] < 0)
i++;
if (arr->A[j] >= 0)
j--;
if (i < j) {
Swap(&arr->A[i], &arr->A[j]);
}
}
}
Principal
int main(){
Array r = { {2,-15, 3,-10,5,6,-44, 55}, 10, 8 };
//Rearrange(&r);
ArrangeNegativeOnLeft(&r);
// Display
cout << "\n Elements are:\n";
for (int i = 0; i < arr.length; i++)
cout << arr.A[i] << " ";
cout << endl;
}