插入排序,居然发现算法导论是MIT出版的,难怪是经典!

本文介绍了一种简单的排序算法——插入排序,并通过一个Java程序实例展示了其工作原理。该程序不仅演示了如何实现插入排序,还提供了排序前后数组的直观展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

         最为关键的是最后排序过程的While循环,在while循环中,只要循环条件成立的话,就不断的往前交换,假如条件不成立,那就是已经到它应该在的位置了,所以要把当前的位置填上原来的元素。

              

import javax.swing.JOptionPane;

public class insertSort
{
 public static void main(String args[])
 {
  int counter=0;
  String output="排序前: ";
  int array[]={2,4,3,89,78,45,98,789,75,50};
  
  for(counter=0;counter<array.length;counter++)
  {
   output+=array[counter]+" ";
  }
  
  InsertSort(array);
  
  output+="/n排序后:";
  
  for(counter=0;counter<array.length;counter++)
  {
   output+=array[counter]+" ";
  }
  
  JOptionPane.showMessageDialog(null,output,"Insert Sort By A Nobody",JOptionPane.PLAIN_MESSAGE);
  System.exit(0);
 }
 
    public static void InsertSort(int array2[])
 {
  int i,j,key;
  
  for(j=2;j<=array2.length;j++)
  {
   key=array2[j-1];
   i=j-1;
   
   while(i>0&&array2[i-1]>key)
    {
     array2[i]=array2[i-1];
     i --;
    }
     array2[i] = key;
   
  }
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值