-
冒泡排序
public class Arry09 { public static void main(String[] args) { //冒泡 从小到大 int[] arr = {1,6,33,86,4,5,3,0}; for (int j = 0; j < arr.length-1; j++) { //决定循环次数 for (int i = 0; i < arr.length-1-j; i++) { //进行排序,arr.length-1-j 其中-1是为防止数组越界,-j是对后面以排好的数据不进行排序,加快速度 if(arr[i]>arr[i+1]) { int temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; //此处进行交换 } } } System.out.println(Arrays.toString(arr)); } }
-
选择排序
public class Arry10 { public static void main(String[] args) { //选择排序,从小到大 int[] arr = {1,6,33,86,4,5,3,0,43}; for (int j = 0; j < arr.length; j++) { int min = arr[j]; int minidex =j; for (int i = j; i < arr.length; i++) { //这里i=j要注意 if(min>arr[i]) { min = arr[i]; minidex = i; } } int temp =arr[j]; arr[j] = arr[minidex]; arr[minidex] =temp; } System.out.println(Arrays.toString(arr)); } }
-
插入排序
public static void main(String[] args) { int arr[] = {4, 1, 3, 2, 7, 8, 9}; for (int i = 1, j, current; i < arr.length; i++) { current = arr[i]; for (j = i - 1; j >= 0 && arr[j] > current; j--) {//这里注意,在循环过后,j的值为-1 arr[j + 1] = arr[j]; } arr[j + 1] = current; } for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } }
-
归并排序
public static void main(String[] args) { int arr[] = {4, 1, 3, 2, 7, 8, 9}; sort(arr,0,arr.length-1); System.out.println(Arrays.toString(arr)); } public static void sort(int[] arr,int lo,int hi){ if(lo>=hi) return; int mid = lo+(hi-lo)/2; sort(arr,lo,mid); sort(arr,mid+1,hi); merge(arr,lo,mid,hi); } public static void merge(int[] arrs,int lo,int mid,int hi){ int[] copy = arrs.clone(); int i=lo,k=lo,j=mid+1; while (k<=hi){ //分为四种情况 if(i>mid){//当前面部分排好序 arrs[k++]=copy[j++]; }else if(j>hi){//当后面部分排好序 arrs[k++] =copy[i++]; }else if(copy[j]<copy[i]){//当后面比前面小 arrs[k++]=copy[j++]; }else {//当前面比后面小 arrs[k++]=copy[i++]; } } }
java实现 冒泡 选择 插入 归并
最新推荐文章于 2024-11-12 18:03:10 发布