帶哨兵的插入排序,帶哨兵插入排序

來源:互聯網
上載者:User

帶哨兵的插入排序,帶哨兵插入排序
插入排序的演算法實現
自己在實現帶有哨兵的插入排序演算法的時候,發現有兩種思路:

  • 在記憶體裡面重新分配一塊比輸入數組inputArray長度大一的temp數組,空出temp數組的第一個位置,然後把inputArray從第emp數組的第二個位置複製進去,既有temp[i+1]=inputArray[i],i<arrayLength,再把第一個位置temp[0]賦值一個足夠小的數字INT_MIN,以temp[0]為哨兵,進行插入排序,最後再把temp數組從第二個元素(temp[1])開始,重新複製到從第一個元素(inputArray[0])開始的inputArray數組裡面,返回。
  • 第二種方法就是每開始一次輸入,就把將要進行插入inputArray[j]的元素賦值給inputArray[0],這樣就可以起到一個哨兵的作用,但是這樣做需要把inputArray數組第一個元素暫存起來,否則數組的第一個元素會丟失,最後再把inputArray[0]進行插入處理...
下面是兩種方案的實現:
第一種實現不是那麼靈活
void insertSort(int inputArray[] ,const int arrayLength){int i,j;int tempArray[arrayLength+1];//inputArray重新複製到tempArray裡面for (i = 0; i < arrayLength; ++i){tempArray[i+1]=inputArray[i];}tempArray[0]=INT_MIN;//下面開始對帶有哨兵的 tempArray進行排序for (i = 1; i <= arrayLength; ++i){int temp = tempArray[i];for (j = i; temp < tempArray[j-1] ; --j){tempArray[j]=tempArray[j-1];}tempArray[j]=temp;}for (i = 0;i<arrayLength; ++i){inputArray[i]=tempArray[i+1];}}

第二種實現
void insertSort(int inputArray[] , const int arrayLength){int i,j;int tempArray[arrayLength+1];//inputArray重新複製到tempArray裡面for (i = 0; i < arrayLength; ++i){tempArray[i+1]=inputArray[i];}tempArray[0]=INT_MIN;//下面開始對帶有哨兵的 tempArray進行排序for (i = 1; i <= arrayLength; ++i){int temp = inputArray[i];for (j = i; temp < tempArray[j-1] ; --j){tempArray[j]=tempArray[j-1];}tempArray[j]=temp;}for (i = 0;i<arrayLength; ++i){inputArray[i]=tempArray[i+1];}}

對兩個插入排序進行實驗:
#include <stdio.h>#include <stdlib.h>
#include <limits.h>void insertSort(int inputArray[],const int arrayLength ){/*...*/}void printArray(const int inputArray[],const int arrayLength){int i;for(i=0;i<arrayLength;++i){printf("%d\t",inputArray[i] );}}int main(int argc, char const *argv[]){int i=0;srand((int)time(NULL));int array[10];for(i=0;i<sizeof(array)/4;++i){array[i]=rand()%100;}printArray(array,sizeof(array)/4);insertSort(array,sizeof(array)/4);printArray(array,sizeof(array)/4);return 0;}

實驗結果:



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.