看书《数据结构与算法分析》看到插入排序时,发现怎么跟冒泡排序这么像,看得我一脸懵逼。看时间复杂度都是O(n2),但是插入排序要比冒泡排序有效率的多,看书上的定义十分痛苦,也区分不了之间有什么区别。
其实两者之间的区别还是很大,冒泡排序的目的是每次排序都能把对应的一个元素送对应的位置,就像冒泡一样,第一次排序把最大的那个送到第一位,第二个把第二大的元素送到第二位置,以此类推。
插入排序时,第一次把前两个元素顺序搞定,第二次把前三个顺序搞定,以此类推。看到一个人把他形容成打扑克(其实感觉麻将也很像,虽然我不是很懂。)。怎么理解,你拿到一副牌,你要理一下牌。一般理牌思路都是,我找一边开始排,由小到大,先排前两张,再排前三张,前三张大小顺序弄好了,再往下排前四张的顺序
怎样理解最直观理解之间的区别,当然用代码来实现了,把每次排序的结果打印出来。顺便我把结果打印出来了。冒泡排序不用做什么解释,这个插入排序我采用两种方式,一个是网上资料常看到的,还一个是教材上的(容易搞混的那个)。分不清楚的同学注意一下j–,这个循环就是第n次我排前n+1张牌的顺序,仔细的推敲一下。
(一)冒泡排序
package test;
import java.util.Arrays;
//写这个比较一下冒泡排序的排序方式,与插入排序对比一下
public class buddle_sort {
public void buddle(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length-1-i; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
}
}
System.out.println("buddle sort "+i+" time out: "+Arrays.toString(arr));
}
}
public static void main(String[] args) {
buddle_sort bs = new buddle_sort();
int arrs [] = {1,2,8,7,5,6,4};
bs.buddle(arrs);
}
}
结果
buddle sort 0 time out: [1, 2, 7, 5, 6, 4, 8]
buddle sort 1 time out: [1, 2, 5, 6, 4, 7, 8]
buddle sort 2 time out: [1, 2, 5, 4, 6, 7, 8]
buddle sort 3 time out: [1, 2, 4, 5, 6, 7, 8]
buddle sort 4 time out: [1, 2, 4, 5, 6, 7, 8]
buddle sort 5 time out: [1, 2, 4, 5, 6, 7, 8]
buddle sort 6 time out: [1, 2, 4, 5, 6, 7, 8]
(二)插入排序
package test;
import java.util.Arrays;
//写这个比较一下插入排序的排序方式,与冒泡排序对比一下
public class insert_sort {
//方式一
public void insert(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int temp = arr[i];
int j = i;
while (j > 0 && arr[j-1] >= temp) {
arr[j] = arr[j-1];
j--;
}
arr[j] = temp;
System.out.println("insert sort "+i+" time out: "+Arrays.toString(arr));
}
}
// 方式二
public void insert2(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int temp =arr[i];
for (int j = i; j > 0 && temp < arr[j-1]; j--) {
int temp2 = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp2;
}
System.out.println("insert2 sort "+i+" time out: "+Arrays.toString(arr));
}
}
public static void main(String[] args) {
insert_sort in = new insert_sort();
int arrs [] = {1,2,8,7,5,6,4};
// in.insert(arrs);
in.insert2(arrs);
}
}
insert sort 1 time out: [1, 2, 8, 7, 5, 6, 4]
insert sort 2 time out: [1, 2, 8, 7, 5, 6, 4]
insert sort 3 time out: [1, 2, 7, 8, 5, 6, 4]
insert sort 4 time out: [1, 2, 5, 7, 8, 6, 4]
insert sort 5 time out: [1, 2, 5, 6, 7, 8, 4]
insert sort 6 time out: [1, 2, 4, 5, 6, 7, 8]
insert2 sort 1 time out: [1, 2, 8, 7, 5, 6, 4]
insert2 sort 2 time out: [1, 2, 8, 7, 5, 6, 4]
insert2 sort 3 time out: [1, 2, 7, 8, 5, 6, 4]
insert2 sort 4 time out: [1, 2, 5, 7, 8, 6, 4]
insert2 sort 5 time out: [1, 2, 5, 6, 7, 8, 4]
insert2 sort 6 time out: [1, 2, 4, 5, 6, 7, 8]
冒泡排序是比较低效率的,遇到比较大的数据时候最好少使用,可以选一些其他高校的排序方法。
以上为我的原创,转载请标明出处,我的个人微信公众号:我是stubborn,有什么建议之类的可以与我沟通联系。(我也要努力把我的个人公众号弄的像点样子。)