Algorithm
Compare each pair of adjacent elements from the beginning of an array and, if they are in reversed order, swap them.
If at least one swap has been done, repeat step 1.
You can imagine that on every step big bubbles float to the surface and stay there. At the step, when no bubble moves, sorting stops. Let us see an example of sorting an array to make the idea of bubble sort clearer.
java code :
public static void bubbleSort(int[] data)
{
int length = data.length;
for (int k = 0; k < length - 1; k++)
{
boolean isSorted = true;
for (int i = 1; i < length - k; i++)
{
if (data[i] < data[i - 1])
{
int tempVariable = data[i];
data[i] = data[i - 1];
data[i - 1] = tempVariable;
isSorted = false;
}
}
if (isSorted)
break;
}
}
Properties :
Stable
O(1) extra space
O(n2) comparisons and swaps
Adaptive: O(n) when nearly sorted
Compare each pair of adjacent elements from the beginning of an array and, if they are in reversed order, swap them.
If at least one swap has been done, repeat step 1.
You can imagine that on every step big bubbles float to the surface and stay there. At the step, when no bubble moves, sorting stops. Let us see an example of sorting an array to make the idea of bubble sort clearer.
java code :
public static void bubbleSort(int[] data)
{
int length = data.length;
for (int k = 0; k < length - 1; k++)
{
boolean isSorted = true;
for (int i = 1; i < length - k; i++)
{
if (data[i] < data[i - 1])
{
int tempVariable = data[i];
data[i] = data[i - 1];
data[i - 1] = tempVariable;
isSorted = false;
}
}
if (isSorted)
break;
}
}
Properties :
Stable
O(1) extra space
O(n2) comparisons and swaps
Adaptive: O(n) when nearly sorted
No comments:
Post a Comment