Write the code to sort an array of integers?
Submitted by: Administrator/* 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.
Submitted by: Administrator
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.
Submitted by: Administrator
Read Online Electrical Engineering Job Interview Questions And Answers
Top Electrical Engineering Questions
☺ | CO2 fire extinguishers are indicated by the color code |
☺ | In a star connected three phase transformer the |
☺ | A single-phase double-wound transformer consists of |
☺ | A residual current device will disconnect under |
☺ | The usual method of insulating core laminations is |
Top Best Engineering Categories
☺ | Mechanical Engineering Interview Questions. |
☺ | Civil Engineering Interview Questions. |
☺ | Chemical Engineering Interview Questions. |
☺ | Electrical Engineering Interview Questions. |
☺ | Automobile Engineering Interview Questions. |