在快速排序算法总结的时候,介绍过基本排序算法包括选择排序、冒泡排序和插入排序。本章把他们三个放在一起总结一下
冒泡排序
思路:每轮循环在未排序数组中冒出最大或最小的到数组的末尾
代码:
public class MaoPaoSort {
public static void main(String[] args){
int[] arrs = {12,3,5,1,7,5,44,80};
mpSort(arrs);
for (int b : arrs){
System.out.print(b + "," );
}
}
public static void mpSort(int[] arrs){
for(int i=arrs.length-1;i>0;i--){
for(int j=0;j<i;j++){
mp(arrs,j,j+1);
}
}
}
public static void mp(int[] arrs,int i,int j){
if(arrs[i] > arrs[j]){
int temp = arrs[i] + arrs[j];
arrs[i] = temp - arrs[i];
arrs[j] = temp - arrs[i];
}
}
}
插入排序
思路:每次把一个未排序的元素插入到已排序的数组中
代码:
public class InserSort {
public static void main(String[] args){
int[] arrs = {12,3,5,1,7,5,44,80};
insertSort(arrs);
for (int b : arrs){
System.out.print(b + "," );
}
}
public static void insertSort(int[] arrs){
for(int i=1;i<arrs.length;i++){
insert(arrs,i);
}
}
public static void insert(int[] arrs, int i){
for(int f = i;f>0;f--){
if(arrs[f] < arrs[f-1]){
int temp = arrs[f] + arrs[f-1];
arrs[f] = temp - arrs[f];
arrs[f-1] = temp - arrs[f];
}else{
break;
}
}
}
}
选择排序
思路:依次遍历数组元素,并将该元素和后面的每个元素比较,如果该元素大于后面的元素,则互换
代码:
public class ChooseSort {
public static void main(String[] args){
int[] arrs = {12,3,5,1,7,5,44,80};
chooseSort(arrs);
for (int b : arrs){
System.out.print(b + "," );
}
}
public static void chooseSort(int[] arrs){
for(int i=0;i<arrs.length-1;i++){
for(int j=i+1;j<arrs.length;j++){
if(arrs[i] > arrs[j]){
int temp = arrs[i] + arrs[j];
arrs[i] = temp - arrs[i];
arrs[j] = temp - arrs[i];
}
}
}
}
}