简单排序算法的C++实现

简单的排序算法

C++实现算法有冒泡排序/选择排序/插入排序/快排。ios

冒泡排序

一只泡泡咕嘟咕嘟……c++

void bubbleSort(int* arr, int len) {
	for (int i = 0; i < len; i++) {
		for (int j = 0; j < len - i-1; j++) {
			if (arr[j] > arr[j + 1])
				swap(arr[j], arr[j + 1]);
		}
	}
}

选择排序

矮子里面拔高个……web

void selectSort(int* arr, int len) {
	for (int i = 0; i < len; i++) {
		int minx = arr[i];
		for (int j = i; j < len; j++) {
			if (arr[j] < arr[i]) {
				swap(arr[i], arr[j]);
			}
		}
	}
}

插入排序

你们给新来的挪挪窝……算法

void insertSort(int* arr, int len) {
	for (int i = 0; i < len - 1; i++) {
		int pre = i;
		int reg = arr[pre+1];
		while (pre >= 0 && reg < arr[pre]) {
			arr[pre + 1] = arr[pre];
			pre--;
		}
		arr[pre+1] = reg;
	}
}

快速排序

一只门槛(pivot)跳来跳去……svg

// How to partition;
int partition(int* arr, int stt, int end) {
	int pivot = (stt + end) / 2;
	while (stt < end) {
		while (arr[stt] < arr[pivot] && stt<end)	stt++;
		if (arr[stt] >= arr[pivot]) {
			swap(arr[stt], arr[pivot]);
			pivot = stt;
		}
		while (arr[end] > arr[pivot] && (stt < end)) end--;
		if (arr[end] <= arr[pivot]) {
			swap(arr[end], arr[pivot]);
			pivot = end;
		}
	}
	return pivot;
}

void quickSort(int* arr, int stt, int end) {
	if (stt >= end) return;
	int pivot = partition(arr, stt, end);
	quickSort(arr, stt, pivot);
	showArr(arr, 5);
	quickSort(arr, pivot+1, end);
}

主函数以下

#include <stdlib.h>
#include <iostream>
#include <algorithm>

using namespace std;

void showArr(int* arr, int len) {
	for (int i = 0; i < len; i++) {
		cout << arr[i] << ' ';
	}printf("\n");
}
int main() {
	int arr[5] = { 5, 2, 3, 11, 7 };
	//bubbleSort(arr, 5);
	//selectSort(arr, 5);
	//insertSort(arr, 5);
	quickSort(arr, 0, 4);

	showArr(arr, 5);
	system("PAUSE");
	return 0;
}