1. 程式人生 > >淺談幾種排序

淺談幾種排序

氣泡排序:

void Bubble(vector<int>&src) {
	int size = src.size();
	for (int i = 0; i < size; i++) {
		for (int j = i + 1; j < size; j++) {
			if (src[i] > src[j])
				swap(src[i], src[j]);
		}
	}
}

簡單選擇排序:每次選擇當前序列中最小值

void Select(vector<int>&src) {
	int size = src.size();
	int min = 0;
	for (int i = 0; i < size; i++) {
		min = src[i];
		for (int j = i+1; j <size; j++) {
			if (min > src[j])
				swap(min, src[j]);
		}
		src[i] = min;
	}
}

插入排序:當前元素往前遍歷,找到合適的位置插入。

void Insert(vector<int>&src) {
	int size = src.size();
	int flag = 0;
	int start = 0;
	int end = 0;
	for (int i = 1; i < size; i++) {
		flag = src[i];
		if (src[i] >= src[i - 1])//如果待插入元素和前一個元素相同則跳過;
			continue;
		for (int j = i-1; j >=0; j--) {
			if (src[i] >= src[j])
			{
				start = j+1;//從當前位置的後一位開始往後移動;
				end = i;//移動到當前需要插入的元素的位置;
				break;
			}
		}
		for (int m = end; m > start; m--) {//
			src[m] = src[m - 1];
		}
		src[start ] = flag;
	}
}

快速排序:先找到一箇中樞然後把它放在正確的位置然後對兩邊的序列進行快速排序;

void Quick(vector<int>&src, int low, int high) {
	if (low >= high)
		return;
	int part = Part(src, low, high);
	Quick(src, low, part);
	Quick(src, part + 1, high);
}
int Part(vector<int>&src,int low,int high) {
	int size = src.size()-1;
	int flag = src[low];
	while (low<high)
	{
		while (flag <= src[high]&& low<high)
			high--;
		src[low] = src[high];
		while (flag >= src[low]&& low<high)
			low++;
		src[high] = src[low];
	}
	src[high] = flag;
	return high;
}

堆排序:先把無序序列建立大頂堆或者小頂堆,然後交換當前序列的最後一個元素和堆頂元素,交換後,把剩下的元素再調整成堆結構;我的程式碼以大頂堆為例。

void HeapDownAdjust(vector<int> &src, int start, int end)
{
	for (int i = start*2+1; i <= end; i=i*2+1) {
		if (i + 1 <= end&&src[i] < src[i + 1]) 
			i++;
		if (src[start] < src[i])
		{
			swap(src[start], src[i]);
			start = i;
		}
		else
			break;
	}
}
void HeapSort(vector<int> &src, int n) {//n是陣列的長度;
	for (int j = n / 2 - 1; j >= 0; j--) {
		HeapDownAdjust(src, j, n-1);
	}
	for (int x = n - 1; x >= 0; x--) {
		swap(src[0], src[x]);
		HeapDownAdjust(src, 0, x - 1);//從第一個節點進行換;
	}
}

歸併排序

void Mergin(vector<int> &src, int left, int mid, int right, vector<int> &re) {
	int i = left, j = mid+1;
	while (i<=mid&&j<=right)
	{
		if (src[i] <=src[j])
		{
			re[left++] = src[i];
			i++;
		}
		else {
			re[left++] = src[j];
			j++;
		}
	}
	if (i > mid) 
		while (j <= right)
			re[left++] = src[j++];
	else
		while (i <= mid)
			re[left++] = src[i++]; 
}
void MerginSort(vector<int> &src, int left, int right, vector<int>&re) {
	if(left < right)
	{
		int mid = (right + left)/2;
		MerginSort(src, left, mid,re);
		MerginSort(src, mid + 1, right,re);
		Mergin(src, left, mid, right,re);
		for (int i = left; i <= right; i++) {
			src[i] = re[i];
		}
	}
}