Java中的冒泡排序
时间:2020-02-23 14:41:16 来源:igfitidea点击:
Java排序是Java面试问题的众多方面之一。
在本文中,我们将看到Java冒泡排序示例并编写冒泡排序程序。
冒泡排序也称为交换排序。
这是最简单的数字排序算法。
气泡排序算法
在冒泡排序中,整数数组从索引0遍历到length-1。
比较第0位的值和第1位的值,如果后者较小,则将其交换。
比较从第0个索引移到第1个长度索引,因此在第一次迭代之后,最后一个索引具有最大的值。
从0th到length-1索引再次重复相同的过程。
在(length-1)迭代之后,对数组进行排序。在最坏情况下,冒泡排序的复杂度为O(n2),在最坏情况下,冒泡排序的复杂度为Ω(n)。
Java中的冒泡排序
这是Java程序中的冒泡排序的实现。
import java.util.Arrays; public class BubbleSort { public static void main(String args[]) { int arr[] = { 5,4,3,2,1 }; int arr1[] = { 1,2,3,4,5 }; System.out.println("Array after sorting in ascending order:"+Arrays.toString(bubbleSortAscending(arr))); System.out.println("Array after sorting in descending order:"+Arrays.toString(bubbleSortDescending(arr1))); } public static int[] bubbleSortAscending(int[] arr){ int temp; for(int i=0; i < arr.length-1; i++){ for(int j=1; j < arr.length-i; j++){ if(arr[j-1] > arr[j]){ temp=arr[j-1]; arr[j-1] = arr[j]; arr[j] = temp; } } //check that last index has highest value in first loop, //second last index has second last highest value and so on System.out.println("Array after "+(i+1)+"th iteration:"+Arrays.toString(arr)); } return arr; } public static int[] bubbleSortDescending(int[] arr){ int temp; for(int i=0; i < arr.length-1; i++){ for(int j=1; j < arr.length-i; j++){ if(arr[j-1] < arr[j]){ temp=arr[j-1]; arr[j-1] = arr[j]; arr[j] = temp; } } //check that last index has highest value in first loop, //second last index has second last highest value and so on System.out.println("Array after "+(i+1)+"th iteration:"+Arrays.toString(arr)); } return arr; } }
上面的程序用于使用冒泡排序算法按升序和降序排序。
上面程序的输出是:
Array after 1th iteration:[4, 3, 2, 1, 5] Array after 2th iteration:[3, 2, 1, 4, 5] Array after 3th iteration:[2, 1, 3, 4, 5] Array after 4th iteration:[1, 2, 3, 4, 5] Array after sorting in ascending order:[1, 2, 3, 4, 5] Array after 1th iteration:[2, 3, 4, 5, 1] Array after 2th iteration:[3, 4, 5, 2, 1] Array after 3th iteration:[4, 5, 3, 2, 1] Array after 4th iteration:[5, 4, 3, 2, 1] Array after sorting in descending order:[5, 4, 3, 2, 1]
正如我们看到的那样,在每个迭代中,最后一个索引将被排序,并且需要(数组长度– 1)次迭代才能进行排序。