Last active
December 12, 2022 11:01
-
-
Save lazuee/4f87ffba1d0b0f82c067ee744affdfac to your computer and use it in GitHub Desktop.
Bubble Sort with Steps in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- 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