思想:
每次选择最大的数,放置到当前的最后位置
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);
}
}
}