归并排序vs归并排序

本文介绍了归并排序和快速排序两种高效排序算法的具体实现。通过C语言实现了归并排序,该算法采用递归方式,借助临时数组进行数据合并;并通过Java展示了快速排序的过程,利用分治策略对数组进行划分,最终实现数组元素的有序排列。

思路:

利用递归,用临时数组保存中间子排序段,再将子排序段归并到原数组,依次递归。

 

#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]);
		}
		
	}
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值