排序算法的实现

一.冒泡排序

#include <cstdio>
#include <cstring>
int main()
{
	int a[10]={5,8,16,7,9,10,14,12,2,1};
	int i,j;
	for(i=0;i<9;i++)
	{
		for(j=0;j<9-i;j++) 
		{
			if(a[j]>a[j+1])
			{
				int t=a[j];
				a[j]=a[j+1];
				a[j+1]=t; 
			}
		}
	}
	for(i=0;i<10;i++)
	{
		printf("%d ",a[i]);
	}
	
	return 0;
}

二.归并排序

#include <bits/stdc++.h>
using namespace std;
const int maxn = 100;
int A[maxn];
void merge(int A[],int l1,int r1,int l2,int r2)
{
	int i = l1,j = l2;
	int t[maxn],index = 0;
	while(i<=r1&&j<=r2)
	{
		if(A[i]<A[j])
			t[index++] = A[i++];
		else
			t[index++] = A[j++];
	} 
	while(i<=r1)
		t[index++] = A[i++];
	while(j<=r2)
		t[index++] = A[j++];
	for(i = 0;i < index;i++)
	{
		A[l1+i] = t[i];
	}
}
void mergesort(int A[],int left,int right)
{
	if(left < right)
	{
		int mid = (left  + right )/2;
		mergesort(A,left,mid);
		mergesort(A,mid+1,right);
		merge(A,left,mid,mid+1,right);	
	}
}

int main()
{
	int i,n;
	cin>>n;
	for(i = 0;i < n;i++)
	{
		cin>>A[i];
	}
	mergesort(A,0,n-1);
	for(i = 0;i < n;i++)
	{
		cout<<A[i]<<" ";
	} 
	cout<<endl;
	return 0;
}

三.快速排序

#include <bits/stdc++.h>
using namespace std;
const int maxn = 100;
int A[maxn];
int partition(int A[],int left,int right)
{
	int temp = A[left];
	while(left < right){
		while(left < right&&A[right] > temp)	right--;
		A[left] = A[right];
		while(left < right&&A[left] <= temp)	    left++;
		A[right] = A[left];
	}
	A[left] = temp;
	return left;
}
void quicksort(int A[],int left,int right)
{
	if(left < right){
		int pos = partition(A,left,right);
		quicksort(A,left,pos-1);
		quicksort(A,pos+1,right);
	}
}
int main()
{
	int i,n;
	cin>>n;
	for(i = 0;i < n;i++)
	{
		cin>>A[i];
	}
	quicksort(A,0,n-1);
	for(i = 0;i < n;i++)
	{
		cout<<A[i]<<" ";
	} 
	cout<<endl;
	return 0;
}

posted on 2018-01-20 16:02  七昂的技术之旅  阅读(140)  评论(0编辑  收藏  举报

导航