Código completo
#include <iostream>
using namespace std;
// Função para rotacionar elementos para manter estabilidade
void rotateRight(int arr[], int start, int end) {
int temp = arr[end];
for (int i = end; i > start; i--) {
arr[i] = arr[i - 1];
}
arr[start] = temp;
}
// Selection Sort Estável
void stableSelectionSort(int arr[], int size) {
cout << "=== SELECTION SORT ESTÁVEL ===" << endl;
cout << "Array inicial: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl << endl;
for (int i = 0; i < size - 1; i++) {
cout << "Iteração " << (i + 1) << ":" << endl;
// Encontrar o menor elemento na parte não ordenada
int minIndex = i;
for (int j = i + 1; j < size; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
cout << " Menor elemento: " << arr[minIndex]
<< " (posição " << minIndex << ")" << endl;
// Em vez de trocar, rotacionar para manter estabilidade
if (minIndex != i) {
cout << " Rotacionando elementos da posição " << i
<< " até " << minIndex << endl;
int minValue = arr[minIndex];
rotateRight(arr, i, minIndex);
cout << " Elemento " << minValue
<< " movido para posição " << i << " mantendo ordem relativa" << endl;
} else {
cout << " Elemento já está na posição correta" << endl;
}
cout << " Array atual: ";
for (int j = 0; j < size; j++) {
if (j <= i) {
cout << "[" << arr[j] << "] ";
} else {
cout << arr[j] << " ";
}
}
cout << endl << endl;
}
cout << "Array final ordenado (estável): ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
// Versão para demonstrar estabilidade com pares (valor, índice original)
struct Element {
int value;
int originalIndex;
};
void printElements(Element arr[], int size, string label) {
cout << label;
for (int i = 0; i < size; i++) {
cout << "(" << arr[i].value << "," << arr[i].originalIndex << ") ";
}
cout << endl;
}
void stableSelectionSortDemo(Element arr[], int size) {
cout << "\n=== DEMONSTRAÇÃO DE ESTABILIDADE ===" << endl;
printElements(arr, size, "Array inicial: ");
for (int i = 0; i < size - 1; i++) {
// Encontrar o menor elemento
int minIndex = i;
for (int j = i + 1; j < size; j++) {
if (arr[j].value < arr[minIndex].value) {
minIndex = j;
}
}
// Rotacionar para manter ordem relativa
if (minIndex != i) {
Element minElement = arr[minIndex];
for (int k = minIndex; k > i; k--) {
arr[k] = arr[k - 1];
}
arr[i] = minElement;
}
cout << "Após iteração " << (i + 1) << ": ";
printElements(arr, size, "");
}
}
int main() {
// Teste básico
int numeros[] = {4, 2, 2, 8, 3, 3, 1};
int tamanho = 7;
stableSelectionSort(numeros, tamanho);
// Demonstração de estabilidade
Element elementos[] = {
{4, 0}, {2, 1}, {2, 2}, {8, 3}, {3, 4}, {3, 5}, {1, 6}
};
stableSelectionSortDemo(elementos, 7);
return 0;
}
Como funciona a versão estável:
Rotação em vez de troca: Em vez de trocar o menor elemento com o primeiro, rotacionamos todos os elementos
Preserva ordem relativa: Elementos iguais mantêm sua ordem original
Complexidade: O(n²) tempo, mas O(n) operações de movimento por iteração
Trade-off: Mais operações de movimento, mas mantém estabilidade
Diferença visual:
Selection Sort normal: [2a, 2b] → [2b, 2a]
(não estável)
Selection Sort estável: [2a, 2b] → [2a, 2b]
(estável)