Question 2 - Bubble Sort
itsLu
c_cpp
2 years ago
808 B
12
Indexable
/* 2- {5, 3, 8, 6, 2, 9, 7, 1}
Show the steps to sort these numbers using bubble sort
algorithm and write the code. */
#include <iostream>
using namespace std;
void Bubble_Sort(int arr[], int n)
{
int p, c, temp;
bool isSwapped;
for (p = 0 ; p < n - 1 ; p++)
{
isSwapped = false;
for (c = 0 ; c < n - p - 1 ; c++)
{
if (arr[c] > arr[c+1])
{
temp = arr[c];
arr[c] = arr[c+1];
arr[c+1] = temp;
isSwapped = true;
}
}
if (isSwapped == false)
break;
}
}
int main ()
{
int arr[8] = {5, 3, 8, 6, 2, 9, 7, 1};
Bubble_Sort(arr, 8);
for (int k = 0 ; k < 8 ; k++)
cout << arr[k] << "\t";
}
Editor is loading...
Leave a Comment