Skip to content

Instantly share code, notes, and snippets.

@christophewang
Last active August 9, 2023 08:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save christophewang/31ff04b338ad60a318db to your computer and use it in GitHub Desktop.
Save christophewang/31ff04b338ad60a318db to your computer and use it in GitHub Desktop.
Bubble Sort in C++
#include <iostream>
void printArray(int *array, int n)
{
for (int i = 0; i < n; ++i)
std::cout << array[i] << std::endl;
}
void bubbleSort(int *array, int n)
{
bool swapped = true;
int j = 0;
int temp;
while (swapped)
{
swapped = false;
j++;
for (int i = 0; i < n - j; ++i)
{
if (array[i] > array[i + 1])
{
temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
swapped = true;
}
}
}
}
int main()
{
int array[] = {95, 45, 48, 98, 485, 65, 54, 478, 1, 2325};
int n = sizeof(array)/sizeof(array[0]);
std::cout << "Before Bubble Sort :" << std::endl;
printArray(array, n);
bubbleSort(array, n);
std::cout << "After Bubble Sort :" << std::endl;
printArray(array, n);
return (0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment