快速排序
int partition (int *a, int left, int right)
{
int pivot = a[right];
int index = left;
int i;
for (i = left; i < right; i++)
{
if (a[i] < pivot)
{
swap (a, i, index);
index++;
}
}
swap (a, index, right);
return index;
}
void qSort (int *a, int left, int right)
{
if (left < right)
{
int pivot = partition (a, left, right);
qSort (a,left,pivot - 1);
qSort (a, pivot + 1, right);
}
}
int main9 ()
{
int a[10]= {9,8,7,6,5,4,3,2,1,0};
int len =sizeof (a) / sizeof(a[0]);
qSort (a, 0, len - 1);
printA (a,len);
return 0;
}
快速排序的思想是,先在数组中随机选择一个数,每个数与之比较,比它大的放在前面,比它小的放在后面。在这儿我们可以用递归,对于一组很大的数,如果要是求第i大,暴力排序的选择将会很耗时间,利用快速思想,可以将数不断的分。下面贴上csdn博客:http://blog.csdn.net/yanzi1225627/article/details/8109035
归并排序:
void merge (int *a, int left, int mid, int right, int *tmp)
{
int i = left;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= right)
{
if (a[i] > a[j])
tmp[k++] = a[j++];
else
tmp[k++] = a[i++];
}
while (i <= mid)
tmp[k++] = a[i++];
while (j <= right)
tmp[k++] = a[j++];
k = 0;
for (i = left; i <= right; i++)
{
a[i] = tmp[k++];
}
}
void mergesort(int *a, int left, int right, int *tmp)
{
if (left >= right)
return;
int mid = (left + right) / 2;
mergesort (a, left, mid, tmp);
mergesort (a, mid + 1, right, tmp);
merge (a, left, mid, right, tmp);
}
int main8 ()
{
int a[10]= {9,8,7,6,5,4,3,2,1,0};
int len =sizeof (a) / sizeof(a[0]);
int tmp[10];
mergesort (a, 0, len - 1, tmp);
printA (a,len);
return 0;
}
归并排序,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表。mergesort函数便是利用递归分别对左右两半边的数进行递归。