快速排序(Quick Sort)
void QuickSort(int a[], int l, int r)
{
int temp = a[l], i = l, j = r;
if(l < r)
{
while(i < j)
{
while(i < j && a[j] > temp)
j--;
if(i < j)
{
a[i] = a[j];
i++;
}
while(i < j && a[i] < temp)
i++;
if(i < j)
{
a[j] = a[i];
j--;
}
}
a[i] = temp;
QuickSort(a, l, i-1);
QuickSort(a, i+1, r);
}
}
冒泡排序(Bubble Sort)
void BubbleSort(int a[], int n)
{
int i, j, temp, flag;
for(i = n-1; i > 0; i--)
{
flag = 0;
for(j = 1;j <= i;j++)
if(a[j-1] < a[j])
{
temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
flag = 1;
}
if(flag == 0)
return;
}
}
希尔排序(Shell Sort)
void ShellSort(int a[], int n)
{
int gap, temp, i, j;
for(gap = n/2; gap > 0; gap/=2)
for(i = gap; i < n; i++)
{
temp = a[i];
for(j = i; j >= gap && a[j-gap] > temp; j-=gap)
a[j] = a[j-gap];
a[j] = temp;
}
}
直接插入排序(Straight Insert Sort)
void StraightInsertSort(itn a[], int n)
{
int temp, i, j;
for(i = 1; i < n; i++)
{
temp = a[i];
j = i-1;
while(j >= 0 && temp < a[j])
{
a[j+1] = a[j];
j--;
}
a[j+1] = temp;
}
}
折半插入排序(Binary Insert Sort)
void BinaryInsertSort(int a[], int n)
{
int i, j, low = 0, high = 0, mid, temp = 0;
for (i = 1; i < n; i++)
{
low = 0;
high = i-1;
temp = a[i];
while(low <= high)
{
mid = (low+high)/2;
if (a[mid] > temp)
high = mid-1;
else
low = mid+1;
}
for (j = i; j > low; j--)
a[j] = a[j-1];
a[low] = temp;
}
}
选择排序(Select Sort)
void SelectSort(int a[], int n)
{
int i, j, k, temp;
for(i = 0; i < n; i++)
{
k = i;
for(j = i+1; j < n; j++)
if(a[k] > a[j])
k = j;
temp = a[i];
a[i] = a[k];
a[k] = temp;
}
}
堆排序(Heap Sort)
void Sift(int a[], int low, int high)
{
int i = low, j = 2*i + 1, temp = a[i];
while(j <= high)
{
if(j < high && a[j] < a[j+1])
j++;
if(temp < a[j])
{
a[i] = a[j];
i = j;
j = 2*i + 1;
}
else
break;
}
a[i] = temp;
}
void HeapSort(int a[], int n)
{
int i, temp;
for(i = n/2-1; i >= 0; i--)
Sift(a, i, n-1);
for(i = n-1; i > 0; i--)
{
temp = a[0];
a[0] = a[i];
a[i] = temp;
Sift(a, 0, i-1);
}
}
二路归并排序(Merge Sort)
void Merge(int a[], int low, int mid,int high)
{
int i, j, k;
int n1 = mid - low + 1;
int n2 = high - mid;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = a[low + i];
for (j = 0; j < n2; j++)
R[j] = a[mid + 1 + j];
i = 0;
j = 0;
k = low;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
a[k] = L[i++];
else
a[k] = R[j++];
k++;
}
while (i < n1)
a[k++] = L[i++];
while (j < n2)
a[k++] = R[j++];
}
void MergeSort(int a[], int low, int high)
{
if (low < high)
{
int mid = (low + high) / 2;
MergeSort(a, low, mid);
MergeSort(a, mid + 1, high);
Merge(a, low, mid, high);
}
}