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
- sort.cpp
- leetcode 日经贴,Cpp code -Sort Colors
- Leetcode 75. Sort Colors (Medium) (cpp)
- Leetcode 147. Insertion Sort List (Medium) (cpp)
- Leetcode 148. Sort List (Medium) (cpp)
- Leetcode 280. Wiggle Sort (Medium) (cpp)
- jzoj 1730. 【10.5NOIP普及模拟】sort(sort.pas/cpp)
- 【算法导论】2-1 插入排序insertion-sort.cpp
- cpp
- CPP
- CPP
- cpp
- cpp
- CPP
- CPP
- (2011.11.29) 05_谢尔排序(Shell's Sort).cpp
- sort
- Sort
- dp.cpp
- 用RSA加密实现Web登录密码加密传输
- 构建robotium+jenkins+TMTS可持续集成自动化测试
- Jquery中AJAX参数详细介绍
- 动态规划——最长非降子序列数组
- sort.cpp
- jquery-validation 学习总结
- gluster常用命令
- HTTP状态301、404、200、304等的意思
- heap.cpp
- 图解 linux TCP/IP协议
- android ListView 几个重要属性
- MovableText(公告牌写字)
- 全自动软化水设备:全自动软化水设备应用范围简介