Created
April 9, 2020 22:22
-
-
Save misterpoloy/00fa478b6a6c6ae021d60636d76701bb to your computer and use it in GitHub Desktop.
Bubble Sort implementation in cpp
This file contains hidden or 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 <iostream> | |
void bubbleSort(int* A, int length) { | |
// Guarantee of iterations to sort the array | |
for (int k = 0; k < length - 1; k++) { // Loop K | |
int flag = 0; | |
// Actual implementation | |
for (int i = 0; i < length - k - 1; i++) { // i < length - 2 | |
if (A[i] > A[i + 1]) { | |
// Swap positions | |
int temp = A[i]; | |
A[i] = A[i + 1]; | |
A[i + 1] = temp; | |
// Loop K improvment | |
flag = 1; | |
} | |
} | |
// Look K optimization | |
if (flag == 0) break; | |
} | |
} | |
int main() { | |
int A[] = { 2, 4, 1, 5, 3, 7 }; | |
bubbleSort(A, 6); | |
for (int n : A) { | |
std::cout << n << std::endl; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment