【算法学习】排序算法 - 简单选择排序

思想:

每次选择最大的数,放置到当前的最后位置

C语言代码

#include<stdio.h>
void array_printf(int a[],int n);
void sort_simple_select(int a[],int n);
 int main(int argc, char const *argv[])
{
	int i,a[5] = {5,4,3,2,10};
	sort_simple_select(a,5);
	array_printf(a,5);
	return 0;
}
void array_printf(int a[],int n){
	int i ;
	for (i = 0; i < n; ++i)
	{
		printf("%d ",a[i]);
	}
	printf("\n");
}
void sort_simple_select(int a[],int n){
	//basic thought
	//** every time SELECT the MAX, and switch the max with the last.
	// example:
	// loop 1:  choose max of [0~n-1] , ==> a[n-1]
	// loop 2:  choose max of [0~n-2] , ==> a[n-2]
	// loop 3:  choose max of [0~n-3] , ==> a[n-3]
	//......
	// loop end: choose max of[0~1] , ==>a[1]
	int max_index;
	int i,j,t;
	for(i=n-1;i>1;i--){
		max_index = 0;
		/*1 choose the index of max*/
		for(j=1; j<=i; j++){
			if( a[j] > a[max_index])
				max_index=j;
		}
		/*2 switch max and last */
		t = a[max_index];
		a[max_index] = a[i];
		a[i]=t;
	}
}


Java代码

import java.util.List;

public class SortSimpleSelect implements Sort {

	@Override
	public void sort(List<Integer> source) {
		int max_index;
		for(int i = source.size()-1;i>=1;i--){
			max_index = 0;
			for(int j=0;j<=i;j++){
				if(source.get(j)>source.get(max_index))
					max_index = j;
			}
			int t = source.get(i);
			source.set(i, source.get(max_index));
			source.set(max_index, t);
		}

	}

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值