冒泡排序 Java 示例
public class BubbleSortExample
{
public static void main(String[] args)
{
// 未排序的数组
Integer[] array = new Integer[] { 12, 13, 24, 10, 3, 6, 90, 70 };
// 使用冒泡排序
bubbleSort(array, 0, array.length);
// 输出排序后的数组
System.out.println(Arrays.toString(array));
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void bubbleSort(Object[] array, int fromIndex, int toIndex)
{
Object d;
for (int i = toIndex - 1; i > fromIndex; i--)
{
boolean isSorted = true;
for (int j = fromIndex; j < i; j++)
{
// 如果大小位置不正确,则交换
if (((Comparable) array[j]).compareTo(array[j + 1]) > 0)
{
isSorted = false;
d = array[j + 1];
array[j + 1] = array[j];
array[j] = d;
}
}
// 不再交换,表明排序完成
if (isSorted)
break;
}
}
}
输出:
[3, 6, 10, 12, 13, 24, 70, 90]
冒泡排序是一种简单而缓慢的排序算法,它重复遍历集合,比较每对相邻元素并在它们的顺序错误时交换它们。
查看更多教程 https://on itroad.com
冒泡排序的性能和复杂度
- 冒泡排序属于 O(n2) 排序算法,对于大数据量的排序效率很低。
- 冒泡排序既稳定又自适应。
- 在几乎排序的数据的情况下,冒泡排序需要 O(n) 时间,但需要至少 2 次遍历数据。
- 如果输入通常按排序顺序排列但偶尔可能有一些乱序元素几乎就位,这可能是实用的。
- 在大集合的情况下应避免冒泡排序。
- 在逆序集合的情况下,它效率不高。
日期:2020-09-17 00:09:31 来源:oir作者:oir
