In: Computer Science
C++ (data structure using c++). please send me copyable file.
Write a program and test a program that translates the following Bubble Sort algorithm to a bubblesort function. The function's prototype is,
void bubblesort(int a[], int size);
Bubble Sort
The inner loop moves the largest element in the unsorted part of the array to the last position of the unsorted part of the array; the outer loop moves the last position of the unsorted part of the array.
The Bubble sort exchanges elements with adjacent elements as it moves the largest element in the unsorted part of the array to its correct position in the sorted part of the array. Once at its correct position an element never moves again. An element may change its position many times before moving to its correct position.
BubbleSort(A)
for outer := A.length - 1 to 1
for inner := 0 to outer –1
if A[inner] > A[inner + 1] then
temp := A[inner]
A[inner] := A[inner + 1]
A[inner + 1 := temp
end if
end for
end for
end BubbleSort
program:
#include <ctime>
#include <iomanip>
#include <iostream>
#include <random>
#include <string>
using namespace std;
bool fill(int a[], int size,
uniform_int_distribution<int>& u,
default_random_engine& e)
{
if (size < 1)
return false;
for (int i = 0; i < size; ++i)
a[i] = u(e);
return true;
}
void show(int a[], int size)
{
for (int i = 0; i < size; ++i)
cout << a[i] << ' ';
}
void bubblesort(int a[], int size)
{
}
int main()
{
const int size = 8;
default_random_engine e;
uniform_int_distribution<int> u(10, 99);
int a1d[size];
fill(a1d, size, u, e);
show(a1d, size); cout << endl;
bubblesort(a1d, size);
show(a1d, size);
cout << endl;
system("pause");
return 0;
}
function:
void bubblesort(int a[], int size)
{
int temp;
for (int i = size-1; i > 0; i--)
{
for (int j = 0; j < i; j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
complete code:
#include <ctime>
#include <iomanip>
#include <iostream>
#include <random>
#include <string>
using namespace std;
bool fill(int a[], int size,
uniform_int_distribution<int>& u,
default_random_engine& e)
{
if (size < 1)
return false;
for (int i = 0; i < size; ++i)
a[i] = u(e);
return true;
}
void show(int a[], int size)
{
for (int i = 0; i < size; ++i)
cout << a[i] << ' ';
}
void bubblesort(int a[], int size)
{
int temp;
for (int i = size-1; i > 0; i--)
{
for (int j = 0; j < i; j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
int main()
{
const int size = 8;
default_random_engine e;
uniform_int_distribution<int> u(10, 99);
int a1d[size];
fill(a1d, size, u, e);
show(a1d, size); cout << endl;
bubblesort(a1d, size);
show(a1d, size);
cout << endl;
system("pause");
return 0;
}
(For any doubt in the solution just leave a comment otherwise please press the like button)