Answer to Question #260706 in C for Shadow

Question #260706

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.

1
Expert's answer
2021-11-03T17:31:03-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 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;
}

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