Test that array with both selection sort and bubble sort.Compute the time taken for each algorithm to complete.Repeat step two and three for 1000, 10000, 100000, and 1000000 random numbers.Plot the results in a graph
#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 arr[] = {1000, 10000, 100000, 1000000};
for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
int a[arr[i]], b[arr[i]];
for (int i=0; i<arr[i]; i++) {
a[i] = b[i] = rand();
}
bubble_sort(a, arr[i]);
selection_sort(b, arr[i]);
}
return 0;
}
Comments
Leave a comment