冒泡排序
最近需要学习数据结构与算法,重新回顾一下之前的内容,补一下之前的课。
冒泡排序个人理解就是让最大的元素浮出水面,像吐泡泡一样一个一个浮出来。
具体是元素两两进行比较如果当前大于另一个元素交换,继续比较,直到最后。
代码主要是Bubble类和测试类完成。
Bubble.class
public class Bubble {
// 对数组a的元素进行排序
public static void sort(Comparable[] a){
for(int i=a.length-1;i>0;i--){
for (int j=0;j0;
}
// 数组元素i和j交换位置
private static void exch(Comparable[] a,int i,int j){
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] =temp;
}
BubbleTest.class
public class BubbleTest {
public static void main(String[] args) {
Integer[] arr = {4,5,6,3,2,1};
Bubble.sort(arr);
System.out.println(Arrays.toString(arr));
}
}
选择排序
选择排序个人理解就是每次将最小元素选出来放到合适的位置。
具体是将第一个元素假设为最小元素,逐次比较,当当前元素大于比较元素时,将最小元素标记索引指到比较元素上,直到真正最小元素出现,将最小元素与第一个元素交换,第一次选择排序完成。
Selection.class
public class Selection {
//对数组a中的元素进行排序
public static void sort(Comparable[] a){
for(int i=0;i<=a.length-2;i++){
//定义一个变量,记录最小元素所在的索引,默认为参与选择排序的第一个所在元素的位置
int minINdex = i;
for(int j=i+1;j0;
}
//数组元素i与j交换位置
private static void exch(Comparable[] a,int i,int j){
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] =temp;
}
}
SelectionTest.class
public class SelectionTest {
public static void main(String[] args) {
//原始数据
Integer[] a = {4,6,8,7,9,2,10,1};
Selection.sort(a);
System.out.println(Arrays.toString(a));
}
}
插入排序
插入排序个人理解就是将无序的元素插入到有序的元素中。
具体做法是假设首元素为有序元素,选第二个为无序,两两比较,首元素大于第二元素交换,此时两个元素为有序组,之后继续选取无序元素比较即可。
Insertion.class
public class Insertion {
// 对数组a的元素进行排序
public static void sort(Comparable[] a){
for (int i=1;i< a.length;i++){
for(int j=i;j>0;j--){
//比较索引j处的值和索引j-1处的值,如果索引j-1的值大于j处的值,则交换数据,如果不大,那么就找到合适的位置了,退出循环即可;
if (greater(a[j-1],a[j])){
exch(a,j-1,j);
}else {
break;
}
}
}
}
// 比较v元素是否大于w元素
private static boolean greater(Comparable v, Comparable w){
return v.compareTo(w)>0;
}
// 数组元素i和j交换位置
private static void exch(Comparable[] a,int i,int j){
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] =temp;
}
}
InsertionTest.class
public class InsertionTest {
public static void main(String[] args) {
Integer[] a= {4,3,2,10,12,1,5,6};
Insertion.sort(a);
System.out.println(Arrays.toString(a));
}
}
写在最后
学东西一定要扎扎实实、认认真真,否则当你在从事所学专业相关的工作时,当年懒散的你,需要现在的你花费更多时间去补习当时的缺项,这样的事情多了之后,人生则一直在补课。



