sort.cpp

来源:互联网 发布:win10必做优化 编辑:程序博客网 时间:2024/05/17 07:16
#include <string>#include <algorithm>#include <time.h>using namespace std;// 冒泡排序void BubbleSort(int a[], int len){if (a == NULL || len <= 0)return;bool swapped;int last = len - 1;do{swapped = false;for (int i = 1; i <= last; i++){// 稳定性体现在这里if (a[i - 1] > a[i]){int tmp = a[i - 1];a[i - 1] = a[i];a[i] = tmp;swapped = true;}}last--;// 每一趟后减少一个带排序个数} while (swapped);}// 快排int partition(int a[], int start, int end){if (start == end)return start;srand((unsigned int)time(NULL));// 在[start,end]随机选择中枢int pivotIndex = (rand() % (end - start + 1)) + start;// a[start]存放中枢Swap(&a[pivotIndex], &a[start]);int storeIndex = start + 1;for (int i = start + 1; i <= end; i++){if (a[i] < a[start]){if (i != storeIndex)Swap(&a[storeIndex], &a[i]);storeIndex++;}}storeIndex--;Swap(&a[start], &a[storeIndex]);return storeIndex;}void QuickSort(int a[], int len){if (a == NULL || len <= 0)return;int pivotIndex = partition(a, 0, len - 1);if (pivotIndex > 0)QuickSort(a, pivotIndex);if (pivotIndex < len - 1)QuickSort(a + pivotIndex + 1, len - pivotIndex - 1);}// 归并排序void Merge(int a[], int tmp[], int start, int mid, int end){int p1 = start;int p2 = mid + 1;int p = start;while (p1 <= mid && p2 <= end){// 归并排序的稳定性体现在这里if (a[p1] <= a[p2])tmp[p++] = a[p1++];elsetmp[p++] = a[p2++];}while (p1 <= mid)tmp[p++] = a[p1++];while (p2 <= end)tmp[p++] = a[p2++];for (int i = start; i <= end; i++)a[i] = tmp[i];}void MergeSortCore(int a[], int tmp[], int start, int end){if (start == end)return;int mid = (start + end) / 2;MergeSortCore(a, tmp, start, mid);MergeSortCore(a, tmp, mid + 1, end);Merge(a, tmp, start, mid, end);}void MergeSort(int a[], int len){if (a == NULL || len <= 0)return;int *tmp = new int[len];MergeSortCore(a, tmp, 0, len - 1);delete[] tmp;}

0 0
原创粉丝点击