目录
1.冒泡
2.选择
3.插入
1.冒泡
其原理外层循环控制循环次数,内层循环拿出相邻的两个数比较
package ffyc.com.shuzu.firsthw;
import java.util.Arrays;
public class MaoPao {
public static void main(String[] args) {
int []a=new int[]{3,2,5,7,57,1,87,78};
int t=0;
for (int i = 0; i < a.length-1; i++) {
for (int j = 0; j < a.length-1-i; j++) {
while(a[j]>a[j+1]){
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
System.out.println(Arrays.toString(a));
}
}
2.选择
其原理外层控制循环次数,内层控制循环制造比较的数
package ffyc.com.shuzu.firsthw;
import java.util.Arrays;
public class XuanZe {
public static void main(String[] args) {
int []a=new int[]{3,2,45,64,23,43,77,98,66};
int t=0;
for (int i = 0; i < a.length-1; i++) {
for (int j = i+1; j < a.length; j++) {
while (a[i]>a[j]){
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
System.out.println(Arrays.toString(a));
}
}
}
3.插入
其原理先拿出索引为1的数去与其前一个数比较
package ffyc.com.shuzu.firsthw;
import java.util.Arrays;
//拿索引为一的数,用这个数去比较
public class Insert {
public static void main(String[] args) {
int[] nums = new int[]{3, 5, 8, 2, 1};
for (int i = 1; i < nums.length; i++) {
int temp = nums[i];
for (int j = i - 1; j >= 0; j--) {
if (nums[j] > temp) {
nums[j + 1] = nums[j];
nums[j] = temp;
}
}
}
System.out.println(Arrays.toString(nums));
}
}



