1.插入排序 O(n*n)
void InsertionSort(int arr[])
{
for(int i=1;i<arr.length();i++)
{
int temp = arr[i];
int j = i;
while((j>0) && (arr[j-1]>temp))
{
arr[j]=arr[j-1];
--j;
}
arr[j] = temp;
}
}
2.快速排序 O(nlog2n)
void QuickSort(int arr[],int left,int right)
{
int i=left;
int j=right;
int piot = arr[left]; //arr[0] as piot
if(i<j)
{
while(i<j)
{
while(i<j && arr[j]>=piot) // 从右向左找第一个小于x的数
j--;
if(i<j)
s[i++]=s[j];
while(i<j && arr[i]<piot)
i++;
if(i<j)
s[j--]=s[i];
}
}
s[i]=piot;
QuickSort(arr,1eft,i-1);
QuickSort(arr,i+1,right);
}
3.冒泡排序 O(n*n)
void BubbleSort(int arr[])
{
for(int i=1;i<arr.length();i++)
{
for(int j=0;j<n-i;j++)
{
if(a[j]>a[j+1])
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
4.希尔排序 0(nlog2n)
void ShellSort(int a[], int n) //d为当前增量
{
int d, i, j, temp;
for(d = n/2;d >= 1;d = d/2)
{
for(i = d; i < n;i++)
{
temp = a[i];
for(j = i - d;(j >= 0) && (a[j] > temp);j = j-d)
{
a[j + d] = a[j];
}
a[j + d] = temp;
}
}
}
5.选择排序
//选择排序, pnData要排序的数据, nLen数据的个数
void SelectSort(int* pnData, int nLen)
{
//i从[0,nLen-1)开始选择,确定第i个元素
for (int i = 0; i < nLen - 1; ++i)
{
int nIndex = i;
for (int j = i + 1; j < nLen; ++j) //遍历剩余数据,选择出当前最小的数据
{
if (pnData[j] < pnData[nIndex])
{
nIndex = j;
}
}
//如果当前最小数据索引不是i,也就是说排在i位置的数据在nIndex处
if (nIndex != i)
{
//交换数据,确定i位置的数据。
int nTemp = pnData[i];
pnData[i] = pnData[nIndex];
pnData[nIndex] = nTemp;
}
}
}
void InsertionSort(int arr[])
{
for(int i=1;i<arr.length();i++)
{
int temp = arr[i];
int j = i;
while((j>0) && (arr[j-1]>temp))
{
arr[j]=arr[j-1];
--j;
}
arr[j] = temp;
}
}
2.快速排序 O(nlog2n)
void QuickSort(int arr[],int left,int right)
{
int i=left;
int j=right;
int piot = arr[left]; //arr[0] as piot
if(i<j)
{
while(i<j)
{
while(i<j && arr[j]>=piot) // 从右向左找第一个小于x的数
j--;
if(i<j)
s[i++]=s[j];
while(i<j && arr[i]<piot)
i++;
if(i<j)
s[j--]=s[i];
}
}
s[i]=piot;
QuickSort(arr,1eft,i-1);
QuickSort(arr,i+1,right);
}
3.冒泡排序 O(n*n)
void BubbleSort(int arr[])
{
for(int i=1;i<arr.length();i++)
{
for(int j=0;j<n-i;j++)
{
if(a[j]>a[j+1])
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
4.希尔排序 0(nlog2n)
void ShellSort(int a[], int n) //d为当前增量
{
int d, i, j, temp;
for(d = n/2;d >= 1;d = d/2)
{
for(i = d; i < n;i++)
{
temp = a[i];
for(j = i - d;(j >= 0) && (a[j] > temp);j = j-d)
{
a[j + d] = a[j];
}
a[j + d] = temp;
}
}
}
5.选择排序
//选择排序, pnData要排序的数据, nLen数据的个数
void SelectSort(int* pnData, int nLen)
{
//i从[0,nLen-1)开始选择,确定第i个元素
for (int i = 0; i < nLen - 1; ++i)
{
int nIndex = i;
for (int j = i + 1; j < nLen; ++j) //遍历剩余数据,选择出当前最小的数据
{
if (pnData[j] < pnData[nIndex])
{
nIndex = j;
}
}
//如果当前最小数据索引不是i,也就是说排在i位置的数据在nIndex处
if (nIndex != i)
{
//交换数据,确定i位置的数据。
int nTemp = pnData[i];
pnData[i] = pnData[nIndex];
pnData[nIndex] = nTemp;
}
}
}