#include <iostream>
#include <vector>
#include <string>
struct Card {
int number;
char id; // to distinguish duplicates
};
// Stable insertion sort for demonstration
void stableInsertionSort(std::vector<Card>& cards) {
for (int i = 1; i < (int)cards.size(); i++) {
Card key = cards[i];
int j = i - 1;
// Move elements greater than key.number one position ahead
while (j >= 0 && cards[j].number > key.number) {
cards[j + 1] = cards[j];
j--;
}
cards[j + 1] = key; // Insert key at correct position
}
}
void printCards(const std::vector<Card>& cards) {
for (const auto& c : cards) {
std::cout << c.number << c.id << " -> ";
}
std::cout << "null" << std::endl;
}
int main() {
std::vector<Card> cards = {{5, 'a'}, {3, ' '}, {5, 'b'}, {2, ' '}, {3, ' '}};
std::cout << "Before sorting:" << std::endl;
printCards(cards);
stableInsertionSort(cards);
std::cout << "After stable sorting by number ascending:" << std::endl;
printCards(cards);
return 0;
}for (int i = 1; i < (int)cards.size(); i++) {
iterate over cards starting from second element
while (j >= 0 && cards[j].number > key.number) {
shift cards greater than key to the right
insert key at correct sorted position
Before sorting:
5a -> 3 -> 5b -> 2 -> 3 -> null
After stable sorting by number ascending:
2 -> 3 -> 3 -> 5a -> 5b -> null