Skip to content

Instantly share code, notes, and snippets.

@lazuee
Last active December 12, 2022 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lazuee/4f87ffba1d0b0f82c067ee744affdfac to your computer and use it in GitHub Desktop.
Save lazuee/4f87ffba1d0b0f82c067ee744affdfac to your computer and use it in GitHub Desktop.
Bubble Sort with Steps in C++
#include <stdio.h>
void bubbleSort(int *arr, int n) {
bool swapped = true;
int j = 0;
int s = 0;
int temp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < n - j; ++i) {
if (arr[i] > arr[i + 1]) {
s++;
printf("\nSteps #%d: ", s);
// From this array
printf("[");
for (int _i = 0; _i < n; _i++) {
if (arr[i] == arr[_i])
printf("( %d", arr[_i]);
if (arr[i + 1] == arr[_i])
printf("%d )", arr[_i]);
if (arr[i] != arr[_i] && arr[i + 1] != arr[_i])
printf("%d", arr[_i]);
printf("%s", (_i == n - 1) ? "" : ", ");
}
printf("] --> ");
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
// To this array
printf("[");
for (int _i = 0; _i < n; _i++) {
if (arr[i] == arr[_i])
printf("( %d", arr[_i]);
if (arr[i + 1] == arr[_i])
printf("%d )", arr[_i]);
if (arr[i] != arr[_i] && arr[i + 1] != arr[_i])
printf("%d", arr[_i]);
printf("%s", (_i == n - 1) ? "" : ", ");
}
printf("]\n");
}
}
}
}
int main() {
int arr[] = {2, 3, 4, 1};
int n = sizeof(arr) / sizeof(arr[0]);
printf("\nUnsorted array: ");
printf("[");
for (int i = 0; i < n; i++) {
printf("%d", arr[i]);
printf("%s", (i == n - 1) ? "" : ", ");
}
printf("]\n");
bubbleSort(arr, n);
printf("\nSorted array: ");
printf("[");
for (int i = 0; i < n; i++) {
printf("%d", arr[i]);
printf("%s", (i == n - 1) ? "" : ", ");
}
printf("]\n");
return 0;
}
--- Result ---
Unsorted array: [2, 3, 4, 1]
Steps #1: [2, 3, ( 4, 1 )] --> [2, 3, ( 1, 4 )]
Steps #2: [2, ( 3, 1 ), 4] --> [2, ( 1, 3 ), 4]
Steps #3: [( 2, 1 ), 3, 4] --> [( 1, 2 ), 3, 4]
Sorted array: [1, 2, 3, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment