思路:
利用递归,用临时数组保存中间子排序段,再将子排序段归并到原数组,依次递归。
#include<stdlib.h>
int temp[100];
void Merge(int* a, int low, int high )
{
int mid, i, j, k;
mid = (low + high) / 2;
for(i = low,j = mid + 1, k = 0; i <= mid && j <= high; k++)
{
if(a[i] <= a[j])
{
temp[k] = a[i];
i++;
}
else
{
temp[k] = a[j];
j++;
}
}
for(; i <= mid; i++)
{
temp[k++] = a[i];
}
for(; j <= high; j++)
{
temp[k++] = a[j];
}
for(i = 0; i < high - low + 1; i++)
{
a[low+i] = temp[i];
}
}
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, high);
}
}
int main()
{
int a[7] = {2,5,3,6,1,9,8};
MergeSort(a, 0, 7);
int i;
for(i = 0; i < 7; i++)
{
printf("%d\n",a[i]);
}
}
package study;
public class QuickSort {
public int sort(int[] a,int low,int high)
{
int temp = a[low];
while(low <= high)
{
while(low <= high && a[high] >= temp)
{
high--;
}
a[low] = a[high];
while(low <= high && a[low] <= temp)
{
low++;
}
a[high] = a[low];
}
a[low] = temp;
return low;
}
public void quickSort(int[] a, int low, int high)
{
if(low < high)
{
int mid = sort(a, low, high);
quickSort(a, low, mid - 1);
quickSort(a, mid + 1, high);
}
}
public static void main(String[] args)
{
int[] a = {2,3,1,7,9};
QuickSort q = new QuickSort();
q.quickSort(a,0,a.length-1);
for(int i = a.length-1; i >=0; i--)
{
System.out.println(a[i]);
}
}
}
本文介绍了归并排序和快速排序两种高效排序算法的具体实现。通过C语言实现了归并排序,该算法采用递归方式,借助临时数组进行数据合并;并通过Java展示了快速排序的过程,利用分治策略对数组进行划分,最终实现数组元素的有序排列。
2167

被折叠的 条评论
为什么被折叠?



