Coder Social home page Coder Social logo

冒泡排序 about easy-tips HOT 1 CLOSED

tigerb avatar tigerb commented on July 17, 2024
冒泡排序

from easy-tips.

Comments (1)

TIGERB avatar TIGERB commented on July 17, 2024

哈哈,下面有优化内循环版的,只是用的while,哈哈~

/**
   * 优化冒泡排序
   *
   * @param  array $value 待排序数组
   * @return array
   */
  function bubble_better($value = [])
  {
    $flag   = true; // 标示 排序未完成
    $length = count($value)-1; // 数组长度
    $index  = $length; // 最后一次交换的索引位置 初始值为最后一位
    while ($flag) {
      $flag = false; // 假设排序已完成
      for ($i=0; $i < $index; $i++) {
        if ($value[$i] > $value[$i+1]) {
          $flag  = true; // 如果还有交换发生 则排序未完成
          $last  = $i; // 记录最后一次发生交换的索引位置
          $tmp   = $value[$i];
          $value[$i] = $value[$i+1];
          $value[$i+1] = $tmp;
        }
      }
      $index = $last;
    }

    return $value;
  }

from easy-tips.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.