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

  • 相关阅读:
    C#Redis哈希Hashes
    C#Redis集合set
    C#Redis列表List
    C#Redis字符串
    入门redis
    C#/Net代码精简优化技巧
    单点登录在asp.net中的简单实现
    sql注入
    数据库sql优化
    常常忘记但是很重要的sql语句
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3150348.html
Copyright © 2011-2022 走看看