排序算法的c++實現——插入排序

插入排序的思想是:給定一個待排序的數組,咱們從中選擇第一個元素做爲有序的基態(單個元素確定是有序的), 而後從剩餘的元素中選擇一個插入到有序的基態中,使插入以後的序列也是有序狀態,重複此過程,直到所有有序爲止。該過程很相似咱們玩撲克牌進行摸牌的過程吧。ios

核心點:git

1  插入排序能夠實現原址排序,不須要藉助額外的空間。github

2 插入排序是穩定排序。redis

3 插入排序的時間複雜度爲O(n*n).數組

 

代碼以下:函數

  /***********************************************************************
  *   Copyright (C) 2019  Yinheyi. <chinayinheyi@163.com>
  *   
  * This program is free software; you can redistribute it and/or modify it under the terms
  * of the GNU General Public License as published by the Free Software Foundation; either 
  * version 2 of the License, or (at your option) any later version.
  
  *   Brief:    
  *   Author: yinheyi
  *   Email: chinayinheyi@163.com
  *   Version: 1.0
  *   Created Time: 2019年05月05日 星期日 21時48分52秒
  *   Modifed Time: 2019年05月09日 星期四 00時14分23秒
  *   Blog: http://www.cnblogs.com/yinheyi
  *   Github: https://github.com/yinheyi
  *   
  ***********************************************************************/
  
  #include <iostream>
  // 插入排序的實現(insertion-sort)
  // 思想:1. 首先從待排序的數組中選擇一個數做爲初始有序狀態的序列;
  //       2. 而後再從數組中選擇下一個數,插入到有序序列中的合適位置,使新的序列也是有序的;
  //       3. 不斷重複這個過程......
  //
  // 核心點:1. 合理安排代碼,使插入排序不須要額外的空間的, 進行原址排序。
  //         2. 如何找到合適的插入位置,以及插入時怎麼移動其它的相關數據問題。
  //
  // 代碼以下, 該函數默認從小到大排序:
  void insertion_sort(int array[], size_t nLength_)
  {
      // 參數的檢測
      if (array == nullptr || nLength_ < 2)
          return;
  
      for (size_t i = 1; i < nLength_; ++i)   // 注意:i是從1開始
      {       
          int _nCurrent = array[i];       // 當前待排序的數字
  
          // 此時,下標爲 0 ~ i-1的數字是有序的. 向後移動比當前序數字大的全部數,爲該數騰出一>  個位置來。  
          int _nLessEqualIndex = i - 1;
          while (_nLessEqualIndex >= 0 && array[_nLessEqualIndex] > _nCurrent)
          {
              array[_nLessEqualIndex + 1] = array[_nLessEqualIndex];
              --_nLessEqualIndex;
          }   
          // 把新數插入到合適的位置
          array[_nLessEqualIndex + 1] = _nCurrent;
      }       
  }
  
  
  // 該函數實現輸出數組內的元素。
  void PrintArray(int array[], size_t nLength_)
  {
      for (size_t i = 0; i < nLength_; ++i)
      {
          std::cout << array[i] << " ";
      }   
      std::cout << std::endl;
  }
  
  
  // 測試
  /***************    main.c     *********************/
>>int main(int argc, char* argv[])
  {
      int array[10] = {4, 1, 7, 9, 1, -2, 43, 34, 903, -23};
  
      std::cout << "排序前:" << std::endl;
      PrintArray(array, 10);
  
      insertion_sort(array, 10);
  
      std::cout << "排序後:" << std::endl;
      PrintArray(array, 10);
  
      return 0;
  }
 
相關文章
相關標籤/搜索