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

  • 相关阅读:
    .dll .h .lib等文件的作用与区别
    [转自]语言黑客的福音
    [转载]一个台湾程序员的心历路程
    Servlet学习总结
    会话跟踪(Cookie & Session)
    JSP学习总结
    人往高处走,水往低处流
    GDI 和GDI+ 混合编程
    常用到的知识
    Sqlite3相关
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3150348.html
Copyright © 2011-2022 走看看