C++ 常見排序-冒泡排序,堆排序,快速排序,選擇排序

#include<iostream>
using namespace std;

//選擇排序,複雜度o(n^2),不穩定
template<typename T>   //定義函數模板,int,double,float都可以
void seletion_sort(vector<T> &arr) {
	for (int i = 0; i < arr.size()-1; ++i) {
		int min_index = i;
		for (int j = i + 1; j < arr.size(); ++j)
			if (arr[min_index] > arr[j])
				min_index = j;
		swap(arr[i], arr[min_index]);//直接使用標準庫函數swap
	}	
}
//插入排序,複雜度o(n^2),穩定
template<typename T>
void insert_sort(vector<T> & arr) {
	for (int i = 1; i < arr.size(); ++i) {
		int key = arr[i];
		int j = i - 1;
		while (j >= 0 && key < arr[j]) {
			arr[j + 1] = arr[j];
			--j;
		}
		arr[j + 1] = key;
	}
}
//冒泡排序
void bubbleSort(int table[],size_t length) {
	for (int i = 0; i < length - 1; i++) {//一個數經歷冒泡循環後,就會確定下來,放到數組最後面,繼續排序前面沒有確定下來的數
		for (int j = 0; j < length - i - 1; j++) {
			if (table[j] > table[j + 1])
				swap(table[j], table[j + 1]);
		}
	}
}
//堆排序
void headAdjust(int table[], int length, int root) {
	while (root*2+1 <= length - 1) {
		int temp = table[root];
		int son_index = root * 2 + 1;
		if (son_index + 1 <= length - 1) {
			if (table[son_index] < table[son_index + 1])
				son_index++;
		}
		if (temp >= table[son_index])
			break;
		else {
			swap(table[root], table[son_index]);
			root = son_index;
		}
	}
}
void heapSort(int table[], size_t length) {
	//建堆
	for (int i = (length - 2) / 2; i >= 0; i--)
		headAdjust(table,length,i);
	//重建堆排序
	for (int i = length ; i >1; i--) {
		swap(table[0], table[i-1]);
		headAdjust(table,i-1,0);
	}
}
//快速排序
void quick_sort(int table[],int left,int right) {
	if (left >= right)
		return;
	int temp = table[left];
	int i = left, j = right;
	while (i < j) {
		while (table[j] >= temp && i < j)
			--j;
		while (table[i] <= temp && i < j)
			++i;
		swap(table[i], table[j]);
	}
	swap(table[i], table[left]);
	quick_sort(table,left, i - 1);
	quick_sort(table,i + 1, right);
}
int main() {
	int a[9] = { 9,1,5,8,3,7,4,6,2 };
	for (auto temp : a)
		cout << temp << " ";
	cout << endl;
	bubbleSort(a, 9);
	for (auto temp : a)
		cout << temp << " ";
	cout << endl;
	heapSort(a, 9);
	for (auto temp : a)
		cout << temp << " ";
	cout << endl;
	quick_sort(a, 0, 8);
	for (auto temp : a)
		cout << temp << " ";
	cout << endl;

	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章