for ( i = 0; i < n-1; i++)
{
for ( j = i+1; j < n; j++)
{
if (a[i]>a[j])
{
}
}
}//选择排序n^2
for ( i = 0; i<n-1; i++)
{
for ( j = 0; j < n-1-i; j++)
{
if (a[j]>a[j+1])
{
}
}
}//冒泡排序n^2
for (i = 1; i < n; i++)
{
for ( j = 0; j < i; j++)
{
if (a[j]>a[i])
{
int tmp=a[i];
for ( k = i; k > j; k++)
{
a[k]=a[k-1];
}
a[j]=tmp;
break;
}
}
}//插入排序n^2
归并排序
#include <iostream>
using namespace std;
void Merge(int a[], int s, int m, int e, int tmp[])
{ //将数组a的局部a[s,m]和a[m+1,e]合并到tmp,并保证tmp有序,然后再拷贝回a[s,m]
//归并操作时间复杂度:O(e-m+1),即O(n)
int pb = 0;
int p1 = s, p2 = m + 1;
while (p1 <= m && p2 <= e)
{
if (a[p1] < a[p2])
tmp[pb++] = a[p1++];
else
tmp[pb++] = a[p2++];
}
while (p1 <= m)
tmp[pb++] = a[p1++];
while (p2 <= e)
tmp[pb++] = a[p2++];
for (int i = 0; i < e - s + 1; ++i)
a[s + i] = tmp[i];
}
void MergeSort(int a[], int s, int e, int tmp[])
{
if (s < e)
{
int m = s + (e - s) / 2;
MergeSort(a, s, m, tmp);
MergeSort(a, m + 1, e, tmp);
Merge(a, s, m, e, tmp);
}
}
int a[10] = {13, 27, 19, 2, 8, 12, 2, 8, 30, 89};
int b[10];
int main()
{
int size = sizeof(a) / sizeof(int);
MergeSort(a, 0, size - 1, b);
for (int i = 0; i < size; ++i)
cout << a[i] << ",";
cout << endl;
return 0;
}
快速排序
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
int a[10] = {1, 23, 45, 68, 24, 78, 6, 3, 56, 99};
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
void Quicksort(int a[], int s, int e)
{
if (s >= e)
return;
int k = a[s];
int i = s, j = e;
while (i != j)
{
while (j > i && a[j] >= k)
--j;
swap(&a[i], &a[j]);
while (j > i && a[i] <= k)
++i;
swap(&a[i], &a[j]);
}
Quicksort(a, s, i - 1);
Quicksort(a, i + 1, e);
}
int main()
{
int size = sizeof(a) / sizeof(int);
Quicksort(a, 0, size - 1);
for (int i = 0; i < size; ++i)
{
cout << a[i] << endl;
}
system("pause");
return 0;
}