zoukankan      html  css  js  c++  java
  • 冒泡排序(JAVA实现)

    很想直接上代码,奈何字数有要求!

      冒泡排序(Bubble Sort),是一种计算机科学领域的较简单的排序算法
      它重复地走访过要排序的元素列,依次比较两个相邻的元素,如果顺序(如从大到小、首字母从Z到A)错误就把他们交换过来。走访元素的工作是重复地进行直到没有相邻元素需要交换,也就是说该元素列已经排序完成。
      这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端(升序或降序排列),就如同碳酸饮料中二氧化碳的气泡最终会上浮到顶端一样,故名“冒泡排序”。

      1.  BubbleSort.java  算法类

     1 /*
     2  * 冒泡排序(数据类型为int型)
     3  */
     4 public class BubbleSort {
     5 
     6     public void bubble_Sort(int[] array,int n) {
     7         for(int p=n-1; p>=0; p--) {
     8             int flag = 0;  
     9             for(int i=0; i<p; i++) {
    10                 if(array[i]>array[i+1]) {
    11                     int tmp = array[i+1];
    12                     array[i+1] = array[i];
    13                     array[i] = tmp;
    14                     flag = 1;
    15                 }
    16             }
    17             if(flag==0) {  //全程无交换 
    18                 break;
    19             }
    20         }
    21     }
    22 }

      2.  Test.java   测试类

     1 /*
     2  * 冒泡排序测试类
     3  */
     4 public class Test {
     5 
     6     public static void main(String[] args) {
     7 
     8         int[] array = {34,8,64,51,32,21};  //初始化数组
     9 
    10         System.out.println("原数组(未排序): ");
    11         for(int i:array) {  //遍历数组
    12             System.out.print(i+" ");
    13         }
    14         
    15         BubbleSort bs = new BubbleSort();
    16         bs.bubble_Sort(array, array.length);
    17         
    18         //排序之后的数组
    19         System.out.println();
    20         System.out.println("冒泡排序之后的数组: ");
    21         for(int i:array) {
    22             System.out.print(i+" ");
    23         }
    24     }
    25 }

      如果这篇文章对你有用的话,希望点个赞,支持一下作者,有什么更好的看法和建议欢迎评论区留言。Bye,下次见!

  • 相关阅读:
    WEB安全测试点总结
    接口自动化-testNG+poi(表格读写实例)
    接口自动化-testNG+httpclient(实例)
    接口自动化-javaTestNG框架-设计思路
    postman接口自动化(三)使用方法
    postman接口自动化(二)tests
    postman接口自动化(一)
    接口自动化-数据驱动-接口用例
    RF(三)robotframework工具介绍
    xpath轴定位详解
  • 原文地址:https://www.cnblogs.com/ljydbk/p/15594154.html
Copyright © 2011-2022 走看看