0% found this document useful (0 votes)
3 views2 pages

CO Bubblesort Steps - CPP

The document contains a C++ program that implements the bubble sort algorithm to sort an array of integers representing cards. It details the sorting process through multiple passes, showing comparisons and swaps made during each pass. Finally, it outputs the sorted array of cards.

Uploaded by

cokianryle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

CO Bubblesort Steps - CPP

The document contains a C++ program that implements the bubble sort algorithm to sort an array of integers representing cards. It details the sorting process through multiple passes, showing comparisons and swaps made during each pass. Finally, it outputs the sorted array of cards.

Uploaded by

cokianryle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <iostream>

using namespace std;

int main() {

// Original cards from the image

int cards[] = {4, 9, 2, 6, 3, 5, 8, 10, 7};

int n = 9;

cout << "Original cards: ";

for (int i = 0; i < n; i++) {

cout << cards[i] << " ";

cout << endl;

// Bubble Sort steps

// Pass 1:

// Compare 4 and 9 -> OK

// Compare 9 and 2 -> swap -> 4 2 9

// Compare 9 and 6 -> swap -> 4 2 6 9

// Compare 9 and 3 -> swap -> 4 2 6 3 9

// Compare 9 and 5 -> swap -> 4 2 6 3 5 9

// Compare 9 and 8 -> swap -> 4 2 6 3 5 8 9

// Compare 9 and 10 -> OK

// Compare 10 and 7 -> swap -> 4 2 6 3 5 8 9 7 10

// Pass 2:

// Compare 4 and 2 -> swap

// Compare 4 and 6 -> OK

// Compare 6 and 3 -> swap

// Compare 6 and 5 -> swap

// Compare 6 and 8 -> OK

// Compare 8 and 9 -> OK

// Compare 9 and 7 -> swap

// Compare 9 and 10 -> OK


// Pass 3:

// Compare 2 and 4 -> OK

// Compare 4 and 3 -> swap

// Compare 4 and 5 -> OK

// Compare 5 and 6 -> OK

// Compare 6 and 8 -> OK

// Compare 8 and 7 -> swap

// Compare 8 and 9 -> OK

// Pass 4:

// All elements already in order

// Actual sorting implementation

for (int i = 0; i < n - 1; i++) {

for (int j = 0; j < n - i - 1; j++) {

if (cards[j] > cards[j + 1]) {

int temp = cards[j];

cards[j] = cards[j + 1];

cards[j + 1] = temp;

cout << "Sorted cards: ";

for (int i = 0; i < n; i++) {

cout << cards[i] << " ";

cout << endl;

return 0;

You might also like