数据结构与算法:十大排序算法之插入排序

数据结构与算法:十大排序算法之插入排序_算法

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;
}
}