zoukankan      html  css  js  c++  java
  • 经典排序算法回顾:插入排序,冒泡排序

    1.冒泡排序:

     1 //第二种方法是通过不遍历有序数组来减少遍历次数,还有第三种方法:同时左右遍历,减少遍历次数
     2 //sort the array bubbleWay:(the normal way)
     3 - (void) InsertSort(int *a){
     4     int n = strlen(a);
     5     for(int i; i<n; i++){
     6         for(int j; j<n-i-1; j++){
     7             if(r[j]>r[j+1]){
     8                 int tmp = a[j];
     9                 a[j] = a[j+1];
    10                 a[j+1] =tmp;
    11             }
    12         }
    13     }
    14 }
    15 
    16 //sort the array bubleWay:(the better way)
    17 - (void) InsertSort(int *a){
    18     int n = strlen(a);
    19     int i = n-1;
    20     while(i>0){
    21         int pos = 0;
    22         for(int j=0; j<i; j++){
    23             if(r[j]>r[j+1]){
    24                 pos = j;
    25                 int tmp = r[j];
    26                 r[j] = r[j+1];
    27                 r[j+1] = tmp;
    28             }
    29         }
    30         i = pos;
    31     }
    32 }

    2.插入排序:(顺带看了一遍,希尔不稳定排序算法原理)

    //还有二分插入,2-路插入排序,只是按照插入的方式不一样的更加高效方法
    //交换的方式可以位移√,可以直接交换
    1
    //sort the array insertWay:(the normal way,the second bubbleWay) 2 - (void) InsertSort(int *a){ 3 int n = strlen(a); 4 if(a == nil || n <= 1)return; 5 for(int i=1; i<n; i++){ 6 int j = i; 7 int tmp = a[i]; 8 while(j && temp<a[j-1]){ 9 a[j]=a[j-1]; 10 j--; 11 } 12 a[j]=a[j-1]; 13 } 14 }
  • 相关阅读:
    Socket网络编程--简单Web服务器(4)
    GCC学习笔记
    字符分隔符'1'(u0001)的困惑
    g++编译时遇到问题undefined reference to
    ROS学习笔记(三)
    cJSON笔记
    ROS学习笔记(二)
    ROS学习笔记(一)
    ffmpeg推流方式采用TCP协议
    Android OS的image文件组成
  • 原文地址:https://www.cnblogs.com/Lxiaolong/p/4063844.html
Copyright © 2011-2022 走看看