Interviewer And Interviewee Guide

Electrical Engineering Interview Question:

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

Read Online Electrical Engineering Job Interview Questions And Answers
Copyright 2007-2024 by Interview Questions Answers .ORG All Rights Reserved.
https://InterviewQuestionsAnswers.ORG.