4. One of the purposes of asymptotic analysis is to compare algorithms. Use the codes of selection and bubble sort program you have written and decide which algorithm performs better.
I. Use the random number generator you programmed and generate a list of 100 items.
#include <rand>
using namespace std;
void bubble_sort(int * a, int n) {
bool swap = true;
while (swap) {
int t;
swap=false;
n--;
for (int i=0; i<n; i++) {
if (a[i+1]<a[i]) {
t=a[i];
a[i]=a[i+1];
a[i+1]=t;
swap=true;
}
}
}
}
void selection_sort(int * a, int n) {
int t;
for (int i=0; i<n-1; i++) {
for (int j=i+1; j<n; j++) {
if (a[i]<a[j]) {
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
}
int main() {
int a[100], b[100];
for (int i=0; i<100; i++) {
a[i] = b[i] = rand();
}
bubble_sort(a, 100);
selection_sort(b, 100);
return 0;
}
Comments
Leave a comment