交换排序的基本思想:根据序列中两个元素的比较结果来对换这两个记录在序列中的位置,也就是说,将键值较大的记录向序列的尾部移动,键值较小的记录向序列的前部移动。
冒泡排序的思想:根据序列中两个元素的比较结果来对换这两个记录在序列中的位置,将键值较大的记录向序列的尾部移动,键值较小的记录向序列的前部移动。因此,每一趟都将较小的元素移到前面,较大的元素自然就逐渐沉到最后面了,也就是说,最大的元素最后才能确定,这就是冒泡。冒泡排序是一种稳定的排序算法,其实现如下:
package keking.sort;
import java.util.Arrays;
/**
* Title: 冒泡排序
* Description: 因为越大的元素会经由交换慢慢"浮"到数列的顶端(最后位置),最大的数最后才确定下来,所以称为冒泡排序
* 时间复杂度:最好情形O(n),平均情形O(n^2),最差情形O(n^2)
* 空间复杂度:O(1)
* 稳 定 性:稳定
* 内部排序(在排序过程中数据元素完全在内存)
* @author keking
*
*/
public class BubbleSort {
public static int[] bubbleSort(int[] target){
if(target != null && target.length > 1){
for(int i = 0; i < target.length; i++){
for(int j = target.length - 1; j > i; j--){
if(target[j] < target[j-1]){
int temp = target[j];
target[j] = target[j-1];
target[j-1] = temp;
}
}
}
}
return target;
}
public static void main(String[] args) {
int[] arr = {12,56,564,564,22,34,12,748,65,385,486,53,2,35,64,};
System.out.println(Arrays.toString(arr));
int[] arr1 = bubbleSort(arr);
System.out.println(Arrays.toString(arr1));
}
}
运行结果:
[12, 56, 564, 564, 22, 34, 12, 748, 65, 385, 486, 53, 2, 35, 64]
[2, 12, 12, 22, 34, 35, 53, 56, 64, 65, 385, 486, 564, 564, 748]