1. 插入排序
1.直接插入排序:不断从无序表中拿出元素插入到有序表中的合适位置。
最好情况下的时间复杂度为O(n).
最坏情况下的时间复杂度为O(n^2).
public int[] InsertSort(int[] R)
{
int j;
for (int i = 2; i < R.Length; i++)
{
R [0] = R [i];
j = i - 1;
if (R [0] < R [j])
{
R [j + 1] = R [j];
j--;
}
R [j + 1] = R [0];
}
return R;
}
2 . 希尔排序.:是对直接插入排序的一种改进。是将待排序的的记录划分为几组,减少参与直接排序的数据量。
时间复杂度大约为(O^1.3)
public int[] ShellSort(int[] R)
{
int j ,temp;
for(int d =R.Length/2; d >= 1; d = d/2)
{
for (int i = d; i < R.Length; i++)
{
temp = R [i];
j = i - d;
if (temp < R [j])
{
R [j + d] = R [j];
}
R [j + d] = temp;
}
}
return R;
}
2. 交换排序
1.冒泡排序 :时间复杂度为O(n^2)
public int[] BubbleSort(int[] R)
{
for (int i = 0; i < R.Length; i++)
{
for (int j = 0; j < R.Length - i - 1; j++)
{
if (R [j] > R [j + 1])
{
int temp = R [j];
R [j] = R [j + 1];
R [j + 1] = temp;
}
}
}
return R;
}
2.快速排序 :是目前认为的最好的内部排序方法。
平均时间复杂度为O(nlog2n)
初始状态越混乱,排序速度越快。越有序越慢,接近冒泡排序
.NET 多个集合类提供的Sort方法就是快速排序
public int QuickSort(int[] R, int low, int high)
{
if (low < high)
{
int i = low, j = high, temp = R [i];
while (i < j)
{
while (i < j && R [j] > temp)
{
j--;
}
R [i] = R [j];
while (i < j && R [i] < temp)
{
i++;
}
R [j] = R [i];
}
R [i] = temp;
QuickSort (R, low, i - 1);
QuickSort (R, i + 1, high);
}
return R;
}
3.选择排序
1.直接选择排序 :时间复杂度为O(n^2)
public int SelectSort(int[] R)
{
int k, temp;
for (int i = 0; i < R.Length; i++)
{
k = i;
for (int j = i + 1; j < R.Length; j++)
{
if (R [j] < R [k])
{
k = j;
}
}
if (i != k)
{
temp = R [i];
R [i] = R [k];
R [k] = R [i];
}
}
return R;
}