The bubble sort works by iterating down an array to be sorted from the first element to the last, comparing each pair of elements and switching their positions if necessary. This process is repeated as many times as necessary, until the array is sorted.
Following is the basic code for bubble sort:
for(int x=0; x<n; x++)
{
for(int y=0; y<n-1; y++)
{
if(array[y]>array[y+1])
{
int temp = array[y+1];
array[y+1] = array[y];
array[y] = temp;
}
}
}
Question #55: Let’s say we have the elements in the array as “2, 3, 1, 5, 4”. What will be the array as soon as ‘x’ in the above algorithm becomes 1?
Options:
- 2, 1, 3, 4, 5
- 1, 2, 3, 4, 5
- 2, 1, 3, 5, 4
- 2, 3, 1, 5, 4
Solution: The correct option is the first one. Steps will be:
2, 3 => 2, 3
3, 1 => 1, 3
3, 5 => 3, 5
5, 4 => 4, 5