HomeWork03.java 1.4 KB

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