1、冒泡排序
1 第一种
int[] arr = { 6, 3, 8, 2, 9, 1 }; 2 System.out.println("排序前数组为:"); 3 for (int num : arr) { 4 System.out.print(num + " "); 5 } 6 for (int i = 0; i < arr.length; i++) {// 外层循环控制排序趟数 7 for (int j = i + 1; j < arr.length; j++) {// 内层循环控制每一趟排序多少次 8 if (arr[i] > arr[j]) { 9 int temp = arr[i]; 10 arr[i] = arr[j]; 11 arr[j] = temp; 12 } 13 } 14 } 15 System.out.println("排序后的数组为:"); 16 for (int num : arr) { 17 System.out.print(num + " "); 18 }
第二种
public static void maoPao(int[] attr){ for(int i = 0;i < attr.length-1;i++){ for (int j = 0;j < attr.length-1-i;j++){ if(attr[j]>attr[j+1]){ int temp; temp = attr[j]; attr[j] = attr[j+1]; attr[j+1] = temp; } } } System.out.println("排序后的attr : "); for (int i = 0;i<attr.length;i++){ System.out.print(attr[i]+" "); } }
2、插入排序
1 int array[] = { 12, 56, 10, 5, 78, 51 }; 2 for (int i = 1; i < array.length; i++) { 3 int temp = array[i]; 4 for (int j = i - 1; j >= 0 && temp < array[j]; j--) { 5 array[j + 1] = array[j]; 6 array[j] = temp; 7 } 8 } 9 for (int i = 0; i < array.length; i++) { 10 System.out.print(array[i] + ","); 11 }
3、递归排序
1 /** 2 * 用递归算法写出 3 * 第一个人10岁,第二个比第一个大两岁,以此类推,求第八个人的年龄? 4 * @param args 5 */ 6 public static void main(String[] args) { 7 // TODO Auto-generated method stub 8 System.out.println(a(8)); 9 } 10 public static int a(int n){ 11 if(n==1) 12 return 10; 13 return a(n-1)+2; 14 }
4、选择排序
第一种: public static void xuanze(int[] ints){ int min,temp; for (int i = 0;i<ints.length-1;i++){ min = i; for (int j = i+1;j < ints.length;j++){ if (ints[j]<ints[min]){ min = j; } } if(min!=i){ temp = ints[i]; ints[i] = ints[min]; ints[min] = temp; } } System.out.println("选择排序后的attr : "); for (int i = 0;i<ints.length;i++){ System.out.print(ints[i]+" "); } } 第二种: int[] attr = {3,24,2,6,4}; for(int i = 0;i < attr.length-1;i++){ for(int j = i+1;j < attr.length;j++){ if(attr[i]>attr[j]){ int temp = attr[i]; attr[i] = attr[j]; attr[j] = temp; } } } for(int i = 0;i < attr.length;i++){ System.out.print(attr[i]+","); }