插入排序
public class InsertSort {
/*
i-1 i
8 3 5 1 4 7
temp =3
第一次: 3(8) 8(3)
temp = 5
第二次: 3 5(8) 8(5)
temp=1
第三次 1(3) 3(5) 5(8) 8(1)
temp=4
第四次 1 3 4(5) 5(8) 8(4)
temp=7
第五次 1 3 4 5 7(8) 8(7)
*/
public static int[] minToMaxInsert(int[] ary) {
for(int i =1;i<ary.length;i++){//循环次数
int temp = ary[i];
int j = 0;
//找位置
for(j = i-1;j>=0;j--){
if(temp<ary[j]){
ary[j+1]=ary[j];
}else{
break;
}
}
ary[j+1]=temp;
System.out.println(Arrays.toString(ary));
}
return ary;
}
public static int[] minToMaxInsert1(int[] ary) {
for(int i =1;i<ary.length;i++){//循环次数
int temp = ary[i];
int j = 0;
//找位置
for(j = i-1;j>=0&&temp<ary[j];j--){
ary[j+1]=ary[j];
}
ary[j+1]=temp;
//System.out.println(Arrays.toString(ary));
}
return ary;
}
选择排序:
public class SelectionSortDemo {
/*分析:
8 3 5 1 4 7
temp = 8
1、 3 8(换位)
temp = 3
2、 3 5
3、 1 3(换位)
4、 1 4
5、 1 7
1
*/
//获取数组中的最小值(temp)
public static int selectionMinValue(int[] ary){
int temp = ary[0];//8获取数组中第一个元素
for(int i =1;i<ary.length ;i++){
//System.out.println(ary[i]);//除一个元素以外的值
if(temp>ary[i]){
temp=ary[i];
}
}
return temp;
}
/*分析:
8 3 5 1 4 7
^ ^
temp = 8
1、 3 8 5 1 4 7
2 ^ ^
3 8 5 1 4 7
3、 1(3) 8 5 3(1) 4 7
^ ^
4、 1(3) 8 5 3(1) 4 7
^ ^
5、 1(3) 8 5 3(1) 4 7
^ ^
*/
//获取第一次排序
public static int[] firstSelectionSort(int[] ary){
for(int i =1;i<ary.length ;i++){
//比对
if(ary[0]>ary[i]){
int temp =ary[i];
ary[i]=ary[0];
ary[0]=temp;
System.out.println(ary[0]+"交换"+ary[i]);
}
}
return ary;
}
/*
8 3 5 1 4 7
temp = 8
i i+1
第一次: 1(3) 8 5 3(1) 4 7
第二次: 1(3) 3(1) 8(5) 5(8)(3(1)) 4 7
第三次: 1(3) 3(1) 4(5(8(8(5)))) 8(5)(5(8)) 5(8(8(5))) 7
第四次:1(3) 3(1) 4(5(8(8(5)))) 5(8(8(5))) 8(5)(5(8)) 7
第五次:1(3) 3(1) 4(5(8(8(5)))) 5(8(8(5))) 7 8(5)(5(8))
*/
public static int[] selectionSort(int[] ary){
for(int i = 0;i<ary.length-1;i++){//外层循环次数
for(int j = i+1;j<ary.length;j++){//取出每次比较最小值
if(ary[i]>ary[j]){//换位子
int temp = ary[i];
ary[i]=ary[j];
ary[j]=temp;
}
}
//System.out.println(Arrays.toString(ary));
}
return ary;
}
冒泡排序:
public class BubbleDemo {
/*分析
8 3 5 1 4 7
i i i+1
1、 3 8
2、 5 8
3、 1 8
4、 4 8
5、 7 8
*/
public static int[] maxBubble(int[] ary){
for(int i = 0;i<ary.length-1;i++){
//第一个值 ary[i] 后边值ary[i+1]
if(ary[i]>ary[i+1]){//相邻元素比较
int temp = ary[i];
ary[i]=ary[i+1];
ary[i+1]=temp;
System.out.println(ary[i]+"交换"+ary[i+1]);
}
}
return ary;
}
/*
8 3 5 1 4 7
i=0
temp = 8 i
第一次 3 5 1 4 7 8 -0
temp = 3
第二次 3 1 4 5 7 -1
temp = 3
第三次 1 3 4 5 -2
temp = 1
第四次 1 3 4 -3
temp = 1
第五次 1 3 -4
*/
public static int[] bubbleSort(int[] ary){
for(int i = 0;i<ary.length-1;i++){//循环次数
for(int j=0;j<ary.length-1-i;j++){//每次相邻比对
if(ary[j]>ary[j+1]){//比
int temp = ary[j];
ary[j]=ary[j+1];
ary[j+1]=temp;
}
}
}
return ary;
}
public static void main(String[] args) {
int[] ary={8,3,5,1,4,7};
ary = BubbleDemo.maxBubble(ary);
System.out.println(Arrays.toString(ary));
}
}