01冒泡排序
void maopao(int* pt,int n)
{
for (int i = n - 1; i > 0; i--)
for (int j = 0; j < i; j++)
if (pt[j] > pt[j + 1])
{
int temp = pt[j];
pt[j] = pt[j + 1];
pt[j + 1] = temp;
}
for (int i = 0; i < n; i++)
cout << pt[i] << " ";
}
02插入排序
void charu(int* pt, int n)
{
for (int i = 1; i < n; i++)
for (int j = i; j > 0; j--)
{
if (pt[j] < pt[j - 1])
{
int temp = pt[j - 1];
pt[j - 1] = pt[j];
pt[j] = temp;
}
}
for (int i = 0; i < n; i++)
cout << pt[i] << " ";
}
03选择排序
void xuanze(int* pt, int n)
{
int tem;
for (int i = 0; i < n; i++)
{
int min = pt[i];
int j = i;
int k= i;
for (; j < n; j++)
if (min > pt[j])
{
min = pt[j]; k = j;
}
tem = pt[i];
pt[i] = pt[k];
pt[k] = tem;
}
for(int i=0;i<n;i++)
cout << pt[i]<<" ";
}
04希尔排序
void xier(int* pt, int n)
{
int* ptem=new int[n];
for (int gap = n / 2; gap >= 1; gap = gap / 2)
{
for (int i = 0; i < gap; i++)
{
for (int i = 0; i < n / gap; i++)
ptem[i] = pt[i * gap];
charutem(ptem, n / gap);
for (int i = 0; i < n / gap; i++)
pt[i * gap] = ptem[i];
}
}
for (int i = 0; i < n; i++)
cout << pt[i] << " ";
}
05快速排序
void kuaisu(int* pt, int start, int end,int n)
{
if (start >= end)![请添加图片描述](https:
return;
int p1 = start;
int p2 = end;
int piv = pt[p1];
while(p1<p2)
{
while (p1 < p2 && pt[p2] >= piv)
{
p2--;
}
pt[p1] = pt[p2];
while (p1 < p2 && pt[p1] <= piv)
{
p1++;
}
pt[p2] = pt[p1];
}
pt[p1] = piv;
kuaisu(pt, start, p1 -1,n);
kuaisu(pt, p1 + 1, end,n);
}
06归并排序
void merge(int arr[], int l, int q, int r) {
int n = r - l + 1;
int* tmp = new int[n];
int i = 0;
int left = l;
int right = q + 1;
while (left <= q && right <= r)
tmp[i++] = arr[left] <= arr[right] ? arr[left++] : arr[right++];
while (left <= q)
tmp[i++] = arr[left++];
while (right <= r)
tmp[i++] = arr[right++];
for (int j = 0; j < n; ++j)
arr[l + j] = tmp[j];
delete[] tmp;
}
void mergesort(int arr[], int l, int r) {
if (l == r)
return;
int q = (l + r) / 2;
mergesort(arr, l, q);
mergesort(arr, q + 1, r);
merge(arr, l, q, r);
}
|