选择排序,插入排序,插入排序二分优化模板

#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;
}
posted @ 2018-12-25 16:09  Western_Trail  阅读(232)  评论(0编辑  收藏  举报