經典排序算法C++實現

#include "pch.h"
#include <iostream>
using namespace std;

//插入排序
void InsertionSort(int A[], int n) {
	for (int i = 1; i < n; i++) {		// 類似抓撲克牌排序
		int get = A[i];					// 右手抓到一張撲克牌
		int j = i - 1;					// 拿在左手上的牌總是排序好的
		while (j >= 0 && A[j] > get) {	// 將抓到的牌與手牌從右向左進行比較
			A[j + 1] = A[j];			// 如果該手牌比抓到的牌大,就將其右移
			j--;						// 直到該手牌比抓到的牌小(或二者相等),將抓到的牌插入到該手牌右邊(相等元素的相對次序未變,所以插入排序是穩定的)
		}
		A[j + 1] = get;
	}
}

//選擇排序
void SelectionSort(int A[], int n) {
	for (int i = 0; i < n - 1; i++) {
		int min = i;
		for (int j = i + 1; j < n; j++) {
			if (A[j] < A[min])
				min = j;
		}
		int temp = A[i];
		A[i] = A[min];
		A[min] = temp;
	}
}

//冒泡排序
void BubbleSort(int A[], int n) {
	for (int i = 0; i < n - 1; i++) {
		for (int j = 0; j < n - 1 - i; j++) {
			if (A[j + 1] < A[j]) {
				swap(A[j], A[j + 1]);
			}
		}
	}
}

//快速排序

//分割函數
int Paritition(int A[], int low, int high) {
	int pivot = A[low];
	while (low < high) {
		while (low < high && A[high] >= pivot) {
			--high;
		}
		A[low] = A[high];
		while (low < high && A[low] <= pivot) {
			++low;
		}
		A[high] = A[low];
	}
	A[low] = pivot;
	return low;
}

//快排母函數
void QuickSort(int A[], int low, int high) {
	if (low < high) {
		int pivot = Paritition(A, low, high);
		QuickSort(A, low, pivot - 1);
		QuickSort(A, pivot + 1, high);
	}
}

int main()
{
	int A[] = { 4, 6, 8, 5, 9, 3, 7, 2, 1 };
	int n = sizeof(A) / sizeof(int);

	//InsertionSort(A, n);
	//SelectionSort(A, n);
	//QuickSort(A, 0, n - 1);
	BubbleSort(A, n);
	cout << "排序結果" << endl;

	for (int i = 0; i < n; i++) {
		cout << A[i];
	}

	return 0;
}


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