zoukankan      html  css  js  c++  java
  • [算法] 冒泡排序、插入排序

     冒泡排序:

     1     public static void bubblesort(int[] a, int n) {        
     2         for(int i = 0; i < n; ++i) {
     3             boolean flag = false;
     4             for(int j = 0; j < n-i-1; ++j) {
     5                 if(a[j] > a[j+1]) {
     6                     int temp = a[j+1];
     7                     a[j+1] = a[j];
     8                     a[j] = temp;
     9                     flag = true;
    10                 }            
    11             }
    12             if(flag == false) break;
    13         }
    14     }

    插入排序:

     1     public static void insertionsort(int[] a,int n) {
     2         for(int i = 1; i < n; ++i) {
     3             int temp = a[i];
     4             int j = i - 1;
     5             for(; j >= 0; --j ) {
     6                 if(a[j] > temp) {
     7                     a[j+1] = a[j];
     8                 }else {break;}
     9                 }
    10                 a[j+1] = temp;    
    11             }
    12         }        

    执行效果:

    冒泡排序花费时间:196ms
    选择排序花费时间:54ms

    我的代码:

     1     public static void insertionsort(int[] a,int n) {
     2         for(int i = 1; i < n; i++) {
     3             int temp = a[i];
     4             for(int j = i; j > 0; j-- ) {
     5                 if(a[j-1] > temp) {
     6                     a[j] = a[j-1];
     7                 }else {break;}
     8                 a[j-1] = temp;    
     9                 }
    10             }
    11         }        

    优化:  

      1、for 循环中 i++ 和 ++i 运行效果一样,但 ++i 效率更高。https://blog.csdn.net/github_37847975/article/details/77369851

      2、第8行赋值放在了第二层循环中,这样每次比较都要给 a[j-1] 赋值,增加了计算量。 

  • 相关阅读:
    函数对象与闭包
    20.03.19作业
    关键字参数,名称空间和作用域
    作业03.18
    函数第二天
    20.03.17作业
    文件
    20.01.16作业
    前端基础
    前端知识(二)
  • 原文地址:https://www.cnblogs.com/cxc1357/p/10035852.html
Copyright © 2011-2022 走看看