冒泡排序
对数组中的原始数据从头到尾多次扫描,相邻两者比较,不符合比较条件时进行交换。
import java.util.Arrays; public class Test2{ public static void main(String[] aaa){ int[] arr1=new int[]{4,3,7,2,9,1,8}; bubbleSort(arr1); System.out.println(Arrays.toString(arr1));//[1, 2, 3, 4, 7, 8, 9] } public static void bubbleSort(int[] arr){ for(int j=0;j<arr.length;j++) for(int i=0;i<arr.length-1;i++) if(arr[i]>arr[i+1]){//升序(从小到大);大于号(>)改成小于号(<)变成降序 int temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; } } }
选择排序
把一轮中的第一个数据作为最小值,从其余的数据中找最小值与之交换。第一轮从arr[0]开始,第二次从arr[1]开始,以此类推。
import java.util.Arrays; public class Test2{ public static void main(String[] aaa){ int[] arr2=new int[]{5,1,7,2,6,8,9,3,4,12}; selectSort(arr2); System.out.println(Arrays.toString(arr2));//[1, 2, 3, 4, 5, 6, 7, 8, 9, 12] } public static void selectSort(int[] arr){ for(int j=0;j<arr.length;j++){ int temp=arr[j]; int tempIndex=j; for(int i=j+1;i<arr.length;i++) if(temp>arr[i]){//升序(从小到大);大于号(>)改成小于号(<)变成降序 temp=arr[i]; tempIndex=i; } arr[tempIndex]=arr[j]; arr[j]=temp; } } }
插入排序
将第一待排序序列第一个元素看做一个有序序列,把第二个元素到最后一个元素当成是未排序序列。从头到尾依次扫描未排序序列,将扫描到的每个元素插入有序序列的适当位置。
import java.util.Arrays; public class Test2{ public static void main(String[] aaa){ int[] arr3=new int[]{7,2,4,8,5,9,1,6,0}; insertSort(arr3); System.out.println(Arrays.toString(arr3));//[0, 1, 2, 4, 5, 6, 7, 8, 9] } public static void insertSort(int[] arr){ for(int j=1;j<arr.length;j++){ for(int i=j-1;i>=0;i--) if(arr[i]>arr[i+1]){//升序(从小到大);大于号(>)改成小于号(<)变成降序 int temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; } else break; } } }
希尔排序(对插入排序的改进)
先按照一定增量进行分组;第一次按照步数为n/2分组,组内按条件比较交换;第二次按照步数为n/4分组,组内比较交换;直到缩小到步数为1.
public static void main(String[] args) { int []arr= {4,1,7,23,12,-100,-20}; shellSort(arr); System.out.println(Arrays.toString(arr)); } public static void shellSort(int[] arr) { int length = arr.length; int temp; for (int step = length / 2; step >= 1; step /= 2) { for (int i = step; i < length; i++) { temp = arr[i]; int j = i - step; while (j >= 0 && arr[j] > temp) { arr[j + step] = arr[j]; j -= step; } arr[j + step] = temp; } } }