Electrical Engineering Question:
Download Questions PDF

Write the code to sort an array of integers?

Answer:

/* 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.

Download Electrical Engineering Interview Questions And Answers PDF

Previous QuestionNext Question
What is the difference between running the following snipet of code on Verilog vs Vera?Write the code for finding the factorial of a passed integer. Use a recursive subroutine?