常见算法
快速排序
#include <iostream>
#include <algorithm>
//快速排序
void qsort(int a[],int left,int right)
{
if(left>=right)return ;
int i=left-1,j=right+1;
int x=a[left+right >>1];
while(i<j)
{
do i++;while(a[i]<x);
do j--;while(a[j]>x);
if(i<j)
{
int t=a[i];a[i]=a[j];a[j]=t;
}
}
qsort(a,left,j);
qsort(a,j+1,right);
}
using namespace std;
int main()
{
int arr[10]={2,3,4,5,6,7,8,9,1};
auto show=[&](int arr[10]){
for(int i=0;i<10;++i)
cout<<arr[i]<<' ';
cout<<endl;
};
show(arr);
qsort(arr,0,9);
show(arr);
return 0;
}
归并排序
#include <iostream>
void merge_sort(int q[], int l, int r) {
if (l >= r) return;
int mid = l + r >> 1;
merge_sort(q, l, mid);
merge_sort(q, mid + 1, r);
int k = 0, i = l, j = mid + 1;
int tmp[r - l + 1]; // 临时数组
while (i <= mid && j <= r)
if (q[i] <= q[j])
tmp[k++] = q[i++];
else
tmp[k++] = q[j++];
while (i <= mid)
tmp[k++] = q[i++];
while (j <= r)
tmp[k++] = q[j++];
for (i = l, j = 0; i <= r; i++, j++)
q[i] = tmp[j];
}
int main() {
int arr[] = {5, 2, 4, 6, 1, 3};
int n = sizeof(arr) / sizeof(arr[0]);
merge_sort(arr, 0, n - 1);
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}
标签:sort,right,int,常见,mid,merge,算法,模板,left
From: https://www.cnblogs.com/AndreaDO/p/18089814