面试时,经常考这三大排序,本程序简单易懂;
选择排序:
package com.cszx.corejava.baseday01homework;
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args) {
int[] arr={1,56,84,71,21,32,0,2,5,8,4}; for(int i=0;i<arr.length-1;i++){ for(int j=i+1;j<arr.length;j++){ if(arr[i]>arr[j]){ int temp; temp=arr[j]; arr[j]=arr[i]; arr[i]=temp; } } } System.out.println(Arrays.toString(arr)); }
}
冒泡排序:
package com.cszx.corejava.baseday01homework;
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) { int[] arr={0,23,15,1,3,4,89,741,45,4}; for(int i=0;i<arr.length-1;i++){ for(int j=0;j<arr.length-i-1;j++){ if(arr[j]>arr[j+1]){ } int temp; temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } System.out.println(Arrays.toString(arr)); }
}
插入排序:
package com.cszx.corejava.baseday01homework;
面试时,经常考这三大排序,本程序简单易懂;
import java.util.Arrays;
public class InsertSort {
public static void main(String[] args) {
int[] arr={2,36,45,8,65,98,65,98,95,62}; int j; for(int i=1;i<=arr.length-1;i++){ int temp=arr[i]; for (j = i-1; j>0&&temp<arr[j]; j--) { } j++; arr[j]=temp; arr[j+1]=arr[j];
}
} System.out.println(Arrays.toString(arr)); }