Algorithms Flashcards
What is the purpose of bubble sort?
To repeatedly swap adjacent elements if they are in the wrong order.
How many passes does bubble sort require?
Up to n-1 passes for an array of size n.
What is the time complexity of bubble sort?
O(n^2) for the worst and average cases.
How do you check if a bubble sort pass made no swaps?
Use a boolean flag.
Can bubble sort handle strings?
Yes, by comparing string values lexicographically.
Is bubble sort stable?
Yes, because it preserves the relative order of equal elements.
How can you optimize bubble sort?
Stop the algorithm if no swaps occur in a pass.
Write a basic bubble sort algorithm for integers.
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;
}
}
}
Why is bubble sort inefficient for large datasets?
Due to its quadratic time complexity.
What data structure works best with bubble sort
Arrays or lists with small datasets.