Algorithms Flashcards

1
Q

What is the purpose of bubble sort?

A

To repeatedly swap adjacent elements if they are in the wrong order.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How many passes does bubble sort require?

A

Up to n-1 passes for an array of size n.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the time complexity of bubble sort?

A

O(n^2) for the worst and average cases.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you check if a bubble sort pass made no swaps?

A

Use a boolean flag.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Can bubble sort handle strings?

A

Yes, by comparing string values lexicographically.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Is bubble sort stable?

A

Yes, because it preserves the relative order of equal elements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How can you optimize bubble sort?

A

Stop the algorithm if no swaps occur in a pass.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Write a basic bubble sort algorithm for integers.

A

for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Why is bubble sort inefficient for large datasets?

A

Due to its quadratic time complexity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What data structure works best with bubble sort

A

Arrays or lists with small datasets.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly