数据结构与算法:十大排序算法之插入排序
原创
©著作权归作者所有:来自51CTO博客作者CMMKK的原创作品,请联系作者获取转载授权,否则将追究法律责任
数据结构与算法:十大排序算法之插入排序
package TopTenSortingAlgorithms;
import java.util.Arrays;
import java.util.Scanner;
public class InsertionSort {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] nums = new int[4];
for (int i = 0; i <nums.length ; i++) {
nums[i]=scanner.nextInt();
}
int[] insertionsort = insertionsort(nums);
System.out.println(Arrays.toString(insertionsort));
}
public static int[] insertionsort(int[] nums){
for (int being = 1; being < nums.length; being++) {
int current=being;
while (current>0&&nums[current]<nums[current-1]){
//从小到大排序,若左边的数大于右边的数 则交换
int tmp=nums[current];
nums[current]=nums[current-1];
nums[current-1]=tmp;
current--;
}
}
return nums;
}
}