服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

选择排序算法的java实现

package utils.sort;

/**

*@author linyco

*利用选择排序法对数组排序,数组中元素必须实现了comparable接口。

*/

public class choosesort implements sortstrategy

   /**

       *对数组obj中的元素以选择排序算法进行排序

       */

       public void sort(comparable[] obj)

       if (obj == null)

                 throw new nullpointerexception("the argument can not be null!");

              }

              comparable tmp = null;

              int index = 0;

              for (int i = 0 ;i < obj.length - 1 ;i++ )

                 index = i;

                     tmp = obj[i];

                     for (int j = i + 1 ;j < obj.length ;j++ )

                     //对邻接的元素进行比较,如果后面的小,就记下它的位置

                            if (tmp.compareto(obj[j]) > 0)

                               tmp = obj[j];   //要每次比较都记录下当前小的这个值!

                                   index = j;

                            }

                     }

                     //将最小的元素交换到前面

                     tmp = obj[i];

                     obj[i] = obj[index];

                     obj[index] = tmp;

                     } }

扫描关注微信公众号