排序算法

选择排序
public class Solution
{
	public void SelectSort(int[] R,int n) {
		int temp;
		int k;
		for(int i=0;i<n;i++) {
			k=i;
			for(int j=i+1;j<n;j++) {
				if(R[j]<R[k]) {
					k=j;
				}
			}
			temp=R[i];
			R[i]=R[k];
			R[k]=temp;
		}
	}
	public static void main(String[] args) {
		Solution s=new Solution();
		int[] R={54,34,12,1,2,55,43,566,2,1};
		s.SelectSort(R,10);
		for(int i=0;i<10;i++) {
			System.out.println(R[i]);
		}
	}

}
冒泡排序:
public void bubbleSort(int[] R,int n) {
		int temp;
		int flag;
		for(int i=n-1;i>=1;--i) {
			flag=0;
			for(int j=1;j<=i;++j) {
				if(R[j]<R[j-1]) {
					temp=R[j];
					R[j]=R[j-1];
					R[j-1]=temp;
					flag=1;
				}
			}
			if(flag==0) {
				return;
			}
		}
	}
归并排序
void mergeSort(int[] R,int low,int high) {
		if(low<high) {
			int mid=(low+high)/2;
			mergeSort(R,low,mid);
			mergeSort(R,mid+1,high);
			merge(R,low,mid,high);
		}
	}


快速排序
public void QuickSort(int[] R,int low,int high) {
		int temp;
		int i=low,j=high;
		if(low<high) {
			temp=R[low];
			while(i!=j) {
				while(j>i&&R[j]>=temp) --j;
				if(i<j) {
					R[i]=R[j];
					++i;
				}
				while(j>i&&R[i]<temp) ++i;
				if(i<j) {
					R[j]=R[i];
					--j;
				}
			}
			R[i]=temp;
			QuickSort(R,low,i-1);
			QuickSort(R,i+1,high);
		}
	}
插入排序
public void insertSort(int[] R,int n) {
		int temp;
		int i,j;
		for(i=1;i<n;i++) {
			temp=R[i];//将待插入关键字暂存于temp中
			j=i-1;
			
			while(j>=0&&temp<R[j]) {
				R[j+1]=R[j];
				--j;
			}
			R[j+1]=temp;
		}

	}
全部评论

相关推荐

04-03 09:32
已编辑
华南农业大学 golang
我的代码出BUG了:"晚点发个邮件调整一下时间",你收到新的邮件没,如果没有收到新的邮件,那就需要进入面试链接留痕,否则系统会判定你迟到
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务