Answers

Question and Answer:

  Home  Electrical Engineering

⟩ Write the code to sort an array of integers?

/* BEGIN C SNIPET */

void bubblesort (int x[], int lim) {

int i, j, temp;

for (i = 0; i < lim; i++) {

for (j = 0; j < lim-1-i; j++) {

if (x[j] > x[j+1]) {

temp = x[j];

x[j] = x[j+1];

x[j+1] = temp;

} /* end if */

} /* end for j */

} /* end for i */

} /* end bubblesort */

/* END C SNIPET */

Some optimizations that can be made are that a single-element array does not need to be sorted; therefore, the "for i" loop only needs to go from 0 to lim-1. Next, if at some point during the iterations, we go through the entire array WITHOUT performing a swap, the complete array has been sorted, and we do not need to continue. We can watch for this by adding a variable to keep track of whether we have performed a swap on this iteration.

 190 views

More Questions for you: