#include <bits/stdc++.h>
using namespace std;
/*****************归并排序*************************/
void merge(vector<int> &a,int l,int mid,int h)
{
vector<int> temp(h-l+1);//临时数组存放排好序的部分
int i=l,j=mid+1,k=0;//i为前面的第一个数,j为后面的第一个数,k为临时数组
while (i<=mid&&j<=h)
{//从头遍历两个数组
if (a[i]<=a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while (i<=mid)
{//前面的数组没有遍历完
temp[k++]=a[i++];
}
while (j<=h)
{//后面的数组没有遍历完
temp[k++]=a[j++];
}
k=0;
while (l<=h)
{//用排好序的临时数组更新原数组
a[l++]=temp[k++];
}
}
void mergeSort(vector<int> &a,int l,int h)
{
if (l<h)
{
int mid=l+(h-l)/2;
mergeSort(a,l,mid);
mergeSort(a,mid+1,h);
merge(a,l,mid,h);
}
}
/*****************交换排序*************************/
//1,冒泡排序 O(n2) 稳定
void bubbleSort(vector<int> *a)
{
int len = a->size();
int temp;
for (int i = 0; i < len - 1; ++i) {
for (int j = 0; j < len - 1 - i; ++j) {
if ((*a)[j+1]<(*a)[j]){
temp = (*a)[j+1];
(*a)[j+1] = (*a)[j];
(*a)[j] = temp;
}
}
}
}
//2,快速排序 O(logn) 不稳定
int getPivoter(vector<int> *a,int low,int high){
int temp = (*a)[low];
while (low<high){
while (low<high&&(*a)[high]>=temp)
high--;
(*a)[low] = (*a)[high];
while (low<high&&(*a)[low]<=temp)
low++;
(*a)[high] = (*a)[low];
}
(*a)[low] = temp;
return low;
}
void quickSort(vector<int> *a,int low,int high){
if (low<high){
int pivoter = getPivoter(a,low,high);
quickSort(a,low,pivoter-1);
quickSort(a,pivoter+1,high);
}
}
/*****************插入排序*************************/
//1,直接插入排序 O(n2) 稳定
void insertSort(vector<int> *a){
int len = a->size();
int temp;
for (int i = 1; i < len; ++i) {
// if ((*a)[i]<(*a)[i-1]){
// int j;
// temp = (*a)[i];
// for (j = i-1; j >= 0&&(*a)[j]>temp; --j) {
// (*a)[j+1] = (*a)[j];
// }
// (*a)[j+1] = temp;
// }
temp=(*a)[i];
int j = i-1;
while (j>=0 && (*a)[j]>temp)
{
(*a)[j+1] = (*a)[j];
j--;
}
(*a)[j+1] = temp;
}
}
//2,折半插入排序 O(nlogn) 稳定
void binInsertSort(vector<int> *a){
int len = a->size();
int temp,low,high,mid;
for (int i = 1; i < len; ++i) {
if ((*a)[i]<(*a)[i-1]){
temp = (*a)[i];
low = 0;
high = i-1;
while (low<=high){
mid = low+(high-low)/2;
if ((*a)[mid]>temp)
high = mid-1;
else
low = mid+1;
}
for (int j = i-1; j >= high+1; --j) {
(*a)[j+1] = (*a)[j];
}
(*a)[high+1] = temp;
}
}
}
//3,希尔排序 不稳定
void sheelSort(vector<int> *a){
int len = a->size();
int space=len/2;
int temp;
while (space>=1){
for (int i = 0; i < space; i++) {//原序列被分为space个子序列,在子序列上进行冒泡排序
for (int j = 0; j < len-space; j+=space) {
for (int k = 0; k < len-space-i; k+=space) {
if((*a)[k+space]<(*a)[k]){
temp = (*a)[k+space];
(*a)[k+space] = (*a)[k];
(*a)[k] = temp;
}
}
}
}
space/=2;
}
}
/*****************选择排序*************************/
//1,简单选择排序 O(n2) 不稳定
void selectSort(vector<int> *a){
int len = a->size();
int min,temp;
for (int i = 0; i < len; ++i) {
min = i;
for (int j = i; j < len; ++j) {
if ((*a)[j]<(*a)[min])
min=j;
}
if (min!=i){
temp = (*a)[i];
(*a)[i] = (*a)[min];
(*a)[min] = temp;
}
}
}
各种排序算法总结
最新推荐文章于 2019-08-19 16:33:56 发布