ProgrammingHardGATE CS · Product company OA
How many swaps does this bubble sort make?
How many swaps does this bubble sort make?
int a[] = {3, 1, 4, 1, 5}, sw = 0;
for (int i = 0; i < 5; i++)
for (int j = 0; j < 4 - i; j++)
if (a[j] > a[j + 1]) { int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t; sw++; }- A. 4
- B. 3
- C. 5
- D. 2
Correct answer: B. 3
Bubble sort swaps only adjacent out-of-order pairs, so it makes one swap per inversion. The inversions are (3, 1), (3, 1) and (4, 1): 3. The equal 1s never swap because the test is strict.
More C Programming questions
- What is printed? c printf("%d %d", strncmp("abc", "abd", 2) == 0, strncmp("ab", "ab0x", 5) == 0);
- uint8t a = 200, b = 100; uint8t c = a + b; What is the value of c?
- With uint32t x = 5u - 7u; what is the value of x?
- uint32t x = 0x00F0A8u; what is x & (0u - x) in hexadecimal?
- uint32t n = 0xB6u; the loop while (n) { n &= n - 1; count++; } runs with count starting at 0. What is count when the loop ends?
- uint16t v = 0xFFFFu; v = v << 4; What is v afterwards?