In: Computer Science
For c++, please do not recycle other peoples code as they do not satisfy the requirements.
Write a program for sorting a list of integers in ascending order using the bubble sort algorithm.
Requirements
Implement the following functions:
Here is the content of the file data.txt.
9
8
4
7
2
9
5
6
1
3
Then reimpelment a function called bubble_sort that has the following prototype.
bubble_sort(int *array, int size, pointer to a function)
Pre condition
array - a pointer to an array of size element.
pointer to function - a pointer to a function that compares two
values (depending on sorting in ascending order or descending
order)
Post condition
Sort the array in ascending or descending based on the the pointer
to a function.
Write the main function to perform the following:
If you have any doubts, please give me comment...
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int readData( int *&arr);
void bsort(int *arr, int last);
void writeToConsole(int * arr, int last);
void bubble_sort(int *arr, int n, int (*func)(int, int));
int less_than(int v1, int v2);
int greater_than(int v1, int v2);
int main()
{
int n, i;
int *arr;
n = readData(arr);
bsort(arr, n);
writeToConsole(arr, n);
//method 2
printf("\n\nAscending order:\n");
bubble_sort(arr, n, &greater_than);
for (i = 0; i < n; i++)
printf("%d ", *(arr+i));
printf("\n\nDescending order:\n");
bubble_sort(arr, n, &less_than);
for (i = 0; i < n; i++)
printf("%d ", *(arr+i));
printf("\n");
delete arr;
return 0;
}
int readData( int *&arr){
int n, num, i;
ifstream in;
in.open("data.txt");
in>>n;
arr = new int[n];
for(i=0; i<n; i++){
in>>num;
*(arr+i) = num;
}
in.close();
return n;
}
void bsort(int *arr, int last){
int i, j, temp;
for(i=0; i<last; i++){
for(j=0; j<last-i-1; j++){
if(*(arr+j)>*(arr+j+1)){
temp = *(arr+j);
*(arr+j) = *(arr+j+1);
*(arr+j+1) = temp;
}
}
}
}
void writeToConsole(int * arr, int last){
cout<<*(arr+0);
for(int i=1; i<last; i++){
cout<<", "<<*(arr+i);
}
cout<<endl;
}
void bubble_sort(int *arr, int n, int (*func)(int v1, int v2))
{
int i, j, temp;
for (i = 0; i < n; i++)
{
for (j = 0; j < n-i-1; j++)
{
if ((*func)(*(arr+j), *(arr+j+1)))
{
temp = *(arr+j);
*(arr+j) = *(arr+j+1);
*(arr+j+1) = temp;
}
}
}
}
int less_than(int v1, int v2)
{
return v1 < v2;
}
int greater_than(int v1, int v2)
{
return v1 > v2;
}