Answer to Question #261084 in C for Shadow

Question #261084

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


1
Expert's answer
2021-11-04T16:26:15-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS