1. 程式人生 > >排序算法的c++實現——插入排序

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

數據 ora gen you china git 核心 ner public

插入排序的思想是:給定一個待排序的數組,我們從中選擇第一個元素作為有序的基態(單個元素肯定是有序的), 然後從剩余的元素中選擇一個插入到有序的基態中,使插入之後的序列也是有序狀態,重復此過程,直到全部有序為止。該過程很類似我們玩撲克牌進行摸牌的過程吧。

核心點:

1 插入排序可以實現原址排序,不需要借助額外的空間。

2 插入排序是穩定排序。

3 插入排序的時間復雜度為O(n*n).

代碼如下:

  /***********************************************************************
  *   Copyright (C) 2019  Yinheyi. <[email protected]>
  *   
  * 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: [email protected]
  *   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; }

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