1. 冒泡排序
1 public class BubbleSort { 2 3 public static void bubbleSort(int data[]) {//冒泡 4 int j = 0; 5 for(int i = 0; i < data.length - 1; i++) { 6 for(j = i + 1; j < data.length; j++) { 7 if(data[i] < data[j]) { 8 swap(data, i, j); 9 } 10 } 11 } 12 } 13 14 public static void swap(int data[], int i, int j) { 15 int temp = data[i]; 16 data[i] = data[j]; 17 data[j] = temp; 18 } 19 20 public static void main(String[] args) { 21 int[] data = {33, 2, 5, 1, 6, 9, 8, 20}; 22 bubbleSort(data); 23 for(int i = 0; i < data.length; i++) { 24 System.out.print(data[i] + " "); 25 } 26 } 27 }
2.选择排序
1 public class SelectSort { 2 3 public static void selectionSort(int data[]) {//选择 4 for(int i = 0; i < data.length - 1; i++) { 5 int max = i; 6 for(int j = i + 1; j < data.length; j ++) { 7 if(data[max] < data[j]) { 8 max = j; 9 } 10 } 11 swap(data, max, i); 12 } 13 } 14 15 public static void swap(int data[], int i, int j) { 16 int temp = data[i]; 17 data[i] = data[j]; 18 data[j] = temp; 19 } 20 21 public static void main(String[] args) { 22 int[] data = {33, 2, 5, 1, 6, 9, 8, 20}; 23 selectionSort(data); 24 for(int i = 0; i < data.length; i++) { 25 System.out.print(data[i] + " "); 26 } 27 } 28 } 29
3.插入排序
1 public class InsertSort { 2 3 public static void insertSort(int[] data) { 4 5 for(int i = 1; i < data.length; i ++){ 6 for(int j = 0; j < i; j++) { 7 if(data[j] < data[i]) { 8 int temp = data[i]; 9 for(int k = i; k > j; k--) { 10 data[k] = data[k-1]; 11 } 12 data[j] = temp; 13 } 14 } 15 } 16 } 17 18 public static void main(String[] args) { 19 int[] data = {33, 2, 5, 1, 6, 9, 8, 20}; 20 insertSort(data); 21 for(int i = 0; i < data.length; i++) { 22 System.out.print(data[i] + " "); 23 } 24 } 25 }