#include<iostream>
#include<vector>
using namespace std;
//冒泡排序
void Bubble_Sort(vector<int> &vec)
{
int temp = 0;
for (int i = 0; i < vec.size()-1; i++)
{
for (int j = 0; j < vec.size()-1-i; j++)
{
if (vec[j] > vec[j + 1])
{
temp = vec[j+1];
vec[j + 1] = vec[j];
vec[j] = temp;
}
}
}
}
//插入排序
void InsertSort(vector<int> &vec)
{
int key = 0;
for (int i = 1; i < vec.size(); i++)
{
key = vec[i];
int j = i - 1;
while (j >= 0 && key < vec[j])
{
vec[j + 1] = vec[j];
--j;
}
vec[j+1] = key;
}
}
//选择排序
void SelectSort(vector<int> &vec)
{
int temp = 0;
for (int i = 0; i < vec.size(); i++)
{
int min = i;
for (int j = i + 1; j < vec.size(); j++)
{
if (vec[j] < vec[min])
min = j;
}
temp = vec[min];
vec[min] = vec[i];
vec[i] = temp;
}
}
//快速排序
void QuickSort(vector<int> &vec,int begin,int end)
{
if (begin < end)
{
int left = begin, right = end, num=vec[left];
while (left < right)
{
while (left < right&&vec[right] > num)
--right;
if (left < right)
vec[left++] = vec[right];
while (left < right&&vec[left] < num)
++left;
if (left < right)
vec[right--] = vec[left];
}
vec[left] = num;
QuickSort(vec, begin, left - 1);
QuickSort(vec, left + 1,end);
}
}
//归并排序
void Merge(vector<int>&vec, int first, int mid, int last, vector<int>&TempVec) //再将二个有序数列合并
{
int begin = first, end = mid+1;
int i = first;
while (begin <= mid&&end <= last)
{
if (vec[begin] < vec[end])
{
TempVec[i] = vec[begin];
begin++;
}
else
{
TempVec[i] = vec[end];
end++;
}
++i;
}
while (begin <= mid)
{
TempVec[i] = vec[begin++];
++i;
}
while (end <= last)
{
TempVec[i] = vec[end++];
++i;
}
for (int j = first; j <= last; j++)
vec[j] = TempVec[j];
}
void MergeSort(vector<int>&vec, int first, int last, vector<int>&TempVec)
{
if (first < last)
{
int mid = (first + last) / 2;
MergeSort(vec, first, mid, TempVec); //左边有序
MergeSort(vec, mid + 1, last, TempVec); //右边有序
Merge(vec, first, mid, last, TempVec); //再将二个有序数列合并
}
}
//堆排序
void Swap(vector<int> &vec, int n, int m)
{
int temp = vec[n];
vec[n] = vec[m];
vec[m] = temp;
}
void MaxHeap(vector<int> & vec,int len)
{
int i = (len - 1) / 2;
for (; i >= 0; i--)
{
int max = i;
if (2 * i + 1 <= len&&vec[2 * i + 1] > vec[i])
max = 2 * i + 1;
if (2 * i + 2 <= len&&vec[i * 2 + 2] > vec[max])
max = 2 * i + 2;
if (max != i)
Swap(vec, i, max);
}
}
void HeapSort(vector<int>& vec)
{
if (!vec.empty())
{
for (int i = vec.size()-1; i >= 0; i--)
{
MaxHeap(vec, i);
Swap(vec, 0, i);
}
}
}
int main()
{
vector<int> iVec{ 1, 5, 6, 2, 76, 8, 10, 9, 3, 47, 89, 23, 45 };
vector<int> rVec(iVec.size(),0);
//Bubble_Sort(iVec);
//InsertSort(iVec);
//SelectSort(iVec);
//QuickSort(iVec,0,iVec.size()-1);
//MergeSort(iVec, 0, iVec.size() - 1, rVec);
HeapSort(iVec);
for (int i = 0; i < iVec.size(); i++)
{
cout << iVec[i] << " ";
}
cout << endl;
return 0;
}
C++之常用排序算法
最新推荐文章于 2024-08-14 11:18:54 发布