第一种:选择法
package test2;
public class tset28 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] m = {
1, 5, 4, 6, 7, 4, 5, 8, 56, 45 };
for (int i = 0; i < m.length; i++) {
int k = i;
for (int j = i + 1; j < m.length; j++) {
if (m[j] < m[k]) {
k = j;
int temp = m[j];
m[j] = m[i];
m[i] = temp;
}
}
}
for (int i = 0; i < m.length; i++) {
System.out.print(m[i] + " ");
}
}
}
第二种:冒泡法
package test2;
public class test28too {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] m = {
1, 5, 4, 6, 7, 4, 5, 8, 56, 45 };
for (int i = 0; i < m.length-1; i++) {
//外层循环控制排序趟数
for (int j = 0; j < m.length - 1 - i; j++) {
//内层循环控制每一趟排序多少次
if (m[j] > m[j + 1]) {
int temp = m[j];
m[j] = m[j + 1];
m[j + 1] = temp;
}
}
}
for (int i = 0; i < m.length; i++) {
System.out.print(m[i] + " ");
}
}
}
第三种:插入法
package List;
import java.util.Scanner;
public class airu {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int[] m = new int[10];
int j;
for (int i = 0; i < m.length; i++) {
m[i] = sc.nextInt();
//从下标为1的元素开始选择合适的位置插入,因为下标为0的只有一个元素,默认是有序的
int temp = m[i];//记录要插入的数据
j = i;
while (j > 0 && temp < m[j - 1]) {
//从已经排序的序列最右边的开始比较,找到比其小的数
m[j] = m[j - 1];//向后挪动
j--;
}
m[j] = temp;//存在比其小的数,插入
}
for (int i : m) {
System.out.println(i);
}
}
}