一、插入排序
void InsertSort(vector<int>&res){
int size=res.size();
for(int i=0;i<size;++i){
for(int j=i;j>0;--j){
if(res[j]<res[j-1]){
swap(res[j],res[j-1]);
}
else{
break;
}
}
}
}
二、堆排序
void Sort(vector<int> &res, int len)
{
int dad = len / 2 - 1;
int son1 = 2*dad+1;
int son2 = 2*dad+2;
for (int i = dad; i >= 0; --i)
{
son1 = 2 * i + 1;
son2 = 2 * i + 2;
if (son1 < len && res[son1] > res[i])
{
swap(res[son1], res[i]);
}
if (son2 < len && res[son2] > res[i])
{
swap(res[son2], res[i]);
}
}
swap(res[0], res[len - 1]);
}
int main()
{
vector<int> res{2, 1, 5, 4, 3};
for (int i = 0; i < res.size() - 1; ++i)
{
Sort(res, res.size() - i);
}
return 0;
}
三、选择排序
for(int i=0;i<len-1;++i)
{
int min=i;
for(int j=i+1;j<len;++j)
{
min=arr[j]<arr[min]?j:min;
}
swap(arr[i],arr[min]);
}
四、归并排序
void MergeSort(vector<int> &res, int start, int end)
{
if (start >= end)
{
return;
}
int mid = (start + end) / 2;
int left1 = start;
int right1 = mid;
int left2 = mid + 1;
int right2 = end;
MergeSort(res, left1, right1);
MergeSort(res, left2, right2);
vector<int> num(end - start + 1, 0);
int pos = 0;
while (left1 <= right1 && left2 <= right2)
{
num[pos++] = res[left1] < res[left2] ? res[left1++] : res[left2++];
}
while (left1 <= right1)
{
num[pos++] = res[left1++];
}
while (left2 <= right2)
{
num[pos++] = res[left2++];
}
for (int i = start; i <= end; ++i)
{
res[i] = num[i - start];
}
}
int main()
{
vector<int> res{2, 1};
MergeSort(res, 0, res.size() - 1);
return 0;
}
五、冒泡排序
void bubble_sort(T arr[], int len) {
int i, j;
for (i = 0; i < len - 1; i++)
for (j = 0; j < len - 1 - i; j++)
if (arr[j] > arr[j + 1])
swap(arr[j], arr[j + 1]);