1. 程式人生 > >選擇排序,插入排序,插入排序二分優化模板

選擇排序,插入排序,插入排序二分優化模板

#include <bits/stdc++.h>
using namespace std;

int a[11] = {10,9,8,6,3,7,2,1,1,4,5};

void selectSort(int a[],int n){     //選擇排序 
    int min,index;
    for(int i = 0;i < n;i++){
        min = a[i];index = i;
        for(int j = i+1;j < n;j++){
            if(min > a[j]) {
                min = a[j];
                index = j;
            }
        }
        a[index] = a[i]; 
        a[i] = min;     
    }
}

void InsertSort(int a[],int n)      //插入排序(陣列) 
{
    for(int i = 1;i < n;i++){
        int key = a[i];         //暫存當前需要插入的值a[i] 
        int j = i - 1;
        while(j >= 0 && a[j] > key){
            a[j+1] = a[j];
            j--;
        }
//      int j;
//      for(j = i-1;j >= 0 && a[j] > key;j--) a[j+1] = a[j];
        a[j+1] = key;
    }   
}

void InsertSortbinary(int a[],int n){           //折半插入排序(二分查詢)
    for(int i = 1;i < n;i++){
        int key = a[i];
        int l = 0,r = i;
        while(l < r){       
            int mid = (l+r)/2;
            if(a[mid] >= key) r = mid;
            else l = mid + 1;
        }
        
        for(int j = i-1;j >= l;j--){
            a[j+1] = a[j];
        }
        a[l] = key;
    }
}

void InsertSort(Linklist L){            //連結串列的插入排序 
    Node* p = L->next,*pre;
    Node* r = p->next;
    p->next = null;
    p = r;
    while(p){
        r = p->next;    //防止斷鏈 
        pre = L;
        while(pre->next->data <= p->data && pre->next != NULL)
            pre = pre->next;
        p->next = pre->next;
        pre->next = p;
        p = r;
    } 
}

int main(void){
    //selectSort(a);
    InsertSortbinary(a,11);
    for(int i = 0;i < 11;i++){
        cout<<a[i]<<" ";
    }
    return 0;
}