【算法学习】排序算法-快速排序

思想:

每次确定要排序列表中一个元素的绝对位置,而后将该列表划分为两部分,两部分分别按照同样的方式进行排序。

C代码

#include "stdio.h"
void array_print(int a[],int n );
void sort_quick(int a[],int start,int end);
int partition(int a[], int start,int end);
void swap(int a[],int s,int t);
void main(){
	int a[]={3,1,18,30,12,11,18,43};
	int n = sizeof(a)/sizeof(int);
	sort_quick(a,0,n-1);
	array_print(a,n);
}
void sort_quick(int a[],int start,int end){
	int m ;
	if(start < end ){
		m = partition(a,start,end);
		sort_quick(a,start,m-1);
		sort_quick(a,m+1,end);
	}
}
int partition(int a[],int start,int end){
	int x = a[end];
	while(start < end){
		while(start<end && a[start]<= x) start++;
		if(start == end) break;
		swap(a,start,end);
		end -- ;
		while(start<end && a[end] >= x) end--;
		if(start == end ) break;
		swap(a,start,end);
		start ++;
	}
	return start;
}
void array_print(int a[],int n ){
	int i;
	for(i=0;i<n;i++)
		printf("%d ",a[i]);
	printf("\n");
}
void swap(int a[],int s,int t){
	int x = a[s];
	a[s] = a[t];
	a[t] = x;
}


JAVA代码

import java.util.List;

public class SortQuick implements Sort {

	@Override
	public void sort(List<Integer> source) {
		sort_quick(source, 0, source.size()-1);
	}
	private void sort_quick(List<Integer> source, int low ,int high){
		if(low < high){
			int m = partition(source, low, high);
			sort_quick(source, low, m-1);
			sort_quick(source, m+1, high);;
		}
	}
	private int partition(List<Integer> source, int low,int high){
		int x = source.get(low);
		while(low<high){
			while(low<high && source.get(high)>=x) high--;
			swap(source, low,high);
			while(low<high && source.get(low)<=x) low++;
			swap(source,low,high);
		}
		return low;
	}
	private void swap(List<Integer> source,int a,int b){
		int x = source.get(a);
		source.set(a, source.get(b));
		source.set(b, x);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值