zoukankan      html  css  js  c++  java
  • 冒泡排序 JAVA版

    冒泡排序

    算法思想是每次从数组末端开始比较相邻俩元素,把第i小的冒泡到数组的第i个位置。i从0一直到N-1从而完成排序。当然也可以从数组开始端开始比较相邻两元素,把第i大的冒泡到第N-i个位置。I从0一直到N-1从而完成排序。

    publicabstractclass Sorter<E extends Comparable<E>>  {

        publicabstractvoid sort(E[] array,int from ,int len);

        publicfinalvoid sort(E[] array)

        {

            sort(array,0,array.length);

        }

        protectedfinalvoid swap(E[] array,int from ,int to)

        {

            E tmp=array[from];

            array[from]=array[to];

            array[to]=tmp;

        }

          publicvoid sort(String helloString, int from, int len) {

                // TODO Auto-generated method stub

               

          }

    }

    publicclass BubbleSorter<E extends Comparable<E>> extends Sorter<E> {

          privatestaticbooleanDOWN=false;

         

          publicfinalvoid bubble_down(E[] array, int from, int len){

                for(int i=from;i<from+len;i++){

                      for(int j=from+len-1;j>i;j--){

                            if(array[j].compareTo(array[j-1])<0){

                                  swap(array,j-1,j);

                            }

                      }

                }

          }

         

          publicfinalvoid bubble_up(E[] array, int from, int len){

                for(int i=from+len-1;i>=from;i--){

                      for(int j=from;j<i;j++){

                            if(array[j].compareTo(array[j+1])<0){

                                  swap(array,j,j+1);

                            }

                      }

                }

          }

         

          @Override

          publicvoid sort(E[] array, int from, int len) {

                // TODO Auto-generated method stub

                if(DOWN){

                      bubble_down(array,from,len);

                }else{

                      bubble_up(array,from,len);

                }

          }

         

          publicstaticvoid main(String[] args){

                 BubbleSorter s1 = new BubbleSorter<String>();

           String[] myStringArray1 = {"2","5","1","9","4"};

           for(int i=0;i<5;i++){

                System.out.println(myStringArray1[i]);

          }

           s1.sort(myStringArray1, 0, 5);

           for(int i=0;i<5;i++){

                System.out.println(myStringArray1[i]);

          }

          }

    }

    Output:

    2

    5

    1

    9

    4

    9

    5

    4

    2

    1

  • 相关阅读:
    HTML5 CSS3简要教程
    WP模拟器修改语言为中文方法
    仿牛华数码频道网整站源码
    backBarButtonItem 颜色/文字修改
    这是html5中WebGL的演示
    CSS3/jQuery创意盒子动画菜单
    bootstrap学习和使用的经验总结
    uploadify插件实现多个图片上传并预览
    绝对炫的幻灯片插件-SKITTER
    制作手机使用的网页图片查看器
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3150348.html
Copyright © 2011-2022 走看看