簡單的排序算法
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]);
}
}
}
選擇排序
矮子裏面拔高個……
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)跳來跳去……
// 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;
}