Manually show how bubble sort algorithm works on the following array:
a) {30,60,20,50,40,10}
b) {30,19,20,25,40,30}
c) {20,60,27,50,21,10}
#include<iostream>
using namespace std;
void SwapInt(int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
//Algorithm that works by repeatedly swapping the adjacent
//elements if they are in wrong order
void BubbleSortAndPrint(int arr[],const int N )
{
cout << "Show every step:\n";
for (int i = 0; i < N-1; i++)
{
for (int j = 0; j < N - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
SwapInt(&arr[j], &arr[j + 1]);
}
}
for (int k = 0; k < N; k++)
{
cout << arr[k] << " ";
}
cout << endl;
}
}
int main()
{
const int N = 6;
int a[] = { 30,60,20,50,40,10};
/*First pass:
{ 30,60,20,50,40,10}->{ 30,20,60,50,40,10}-> { 30,20,60,50,40,10}->
{ 30,20,50,60,40,10}->{ 30,20,50,40,60,10}->{ 30,20,50,40,10,60}
Second pass:
{ 30,20,50,40,10,60}->{ 20,30,50,40,10,60}->{ 20,30,40,50,10,60}->
{ 20,30,40,10,50,60}
Third pass:
{ 20,30,40,10,50,60}->{ 20,30,10,40,50,60}
Fourth pass:
{ 20,30,10,40,50,60}->{ 20,10,30,40,50,60}
fifth pass:
{ 20,30,10,40,50,60}->{ 10,20,30,40,50,60}
*/
BubbleSortAndPrint(a,N);
int b[] = { 30,19,20,25,40,30};
BubbleSortAndPrint(b,N);
int c[] = { 20,60,27,50,21,10};
BubbleSortAndPrint(c, N);
}
Comments
Leave a comment