| 12345678910111213141516171819202122232425262728293031 |
- /**
- * @author WanJl
- * @version 1.0
- * @title HomeWork03
- * @description 7月16日作业-插入排序-升序
- * @create 2026/7/17
- */
- public class HomeWork03 {
- public static void main(String[] args) {
- /*
- 把一个数组分为两部分,studentScores[0](已排序部分) 和 studentScores[1]~studentScores[studentScores.length-1](未排序部分)
- 然后,从未排序部分取出第1个元素,跟已排序部分从最后一个元素开始比较,知道找到比这个元素小的元素,放到它后面
- */
- int[] studentScores={88, 72, 93, 65, 81, 97, 78, 85};
- //从第2个元素studentScores[1]开始,因为假设 studentScores[0]第1个元素是已排序部分
- for (int i = 1; i <studentScores.length; i++) {
- //设定当前要插入的元素就是本轮的i对应的元素
- int current=studentScores[i];
- //设定已排序部分的最后一个元素
- int j=i-1;
- //从后往前扫描已排序部分,寻找到插入的位置
- //如果已排序部分的元素大于current,就往后移动一位
- while (j>=0&studentScores[j]>current){
- studentScores[j+1]=studentScores[j]; //studentScores[j]往后移动1位
- j--;
- }
- //这个时候,j+1 就是current应该插入的位置
- studentScores[j+1]=current;
- }
- }
- }
|