zoukankan      html  css  js  c++  java
  • 经典排序之 冒泡排序

    冒泡排序和选择排序一样是我们接触相对早的一种排序算法。下面简单讲解一下冒泡排序的思想:

    算法思想:

      冒泡排序,顾名思义,排序的过程就像气泡在水里上升一样。就是对数组进行不断地扫描,每当遇到比标记的数据大的元素就交换两个数据。这样扫描一遍之后就会产生一个最小或最大的元素位于最终的位置上。之后进行第二遍扫描,第三遍......最终完成

      冒泡排序是一种稳定的算法,他的最好时间复杂度是O(n),就是在基本有序的情况下。最坏和一般情况下为O(n2)。

    算法实现:

     1 #include<iostream>
     2 using namespace std;
     3 
     4 void swap(int &a, int &b){
     5     int temp = a;
     6     a = b;
     7     b = temp;
     8 } 
     9 void bubbleSort(int *data, int length){
    10     
    11     if(data == NULL || length < 0){
    12         return ;
    13     }
    14     
    15     for(int i = 0; i < length; i++){               //扫描遍数
    16         for(int j = i; j < length; j++){           //每一遍之中比较,进行交换
    17             if(data[i] > data[j]){
    18                 swap(data[i], data[j]);
    19             }
    20         } 
    21     }
    22 }
    23 
    24 int main(){                                            //测试例子
    25     int str[] = {34, 23, 4, 78, 1, 0, 45, 9, 33, 6, 234};
    26     int len = sizeof(str) / sizeof(int);
    27     bubbleSort(str, len);
    28     
    29     for(int k = 0; k < len; k++){
    30         cout<< str[k]<< ' '; 
    31     } 
    32     
    33     return 0;
    34 }
  • 相关阅读:
    javascript:Storage 接口
    javascript:CORS 通信
    javascript:同源限制
    javascript:XMLHttpRequest 对象
    javascript:Cookie
    javascript:Navigator 对象,Screen 对象
    javascript:window 对象
    javascript:浏览器环境概述
    javascript:GlobalEventHandlers 接口
    javascript:其他常见事件
  • 原文地址:https://www.cnblogs.com/dormant/p/5317293.html
Copyright © 2011-2022 走看看