您的位置:首页 > 编程语言 > Java开发

基于JAVA的排序算法之二--选择排序

2014-12-25 13:08 369 查看
二、选择排序

1. 基本思想:

  每一趟从待排序的数据元素中选出最小(或最大)的一个元素,顺序放在已排好序的数列的最后,直到全部待排序的数据元素排完。

2. 排序过程:

【示例】:

  初始关键字[49 38 65 97 76 13 27 49]

第一趟排序后13 [38 65 97 76 49 27 49]

第二趟排序后13 27 [65 97 76 49 38 49]

第三趟排序后13 27 38 [97 76 49 65 49]

第四趟排序后13 27 38 49 [49 97 65 76]

第五趟排序后13 27 38 49 49 [97 97 76]

第六趟排序后13 27 38 49 49 76 [76 97]

第七趟排序后13 27 38 49 49 76 76 [ 97]

最后排序结果13 27 38 49 49 76 76 97

java代码实现:

 

01.   

04.public class SelectSort
{      

05.     

06.   
     

13.    public
void select(Integer[] array)
{      

14.       
int
minIndex;//最小索引      

15.       
     

21.       
for (int i=0; i

22.           
minIndex =
i;//假设每轮第一个元素为最小元素      

23.           
//从假设的最小元素的下一元素开始循环      

24.           
for (int j=i+1;j

25.               
//如果发现有比当前array[smallIndex]更小元素,则记下该元素的索引于smallIndex中      

26.        
       if
((array[j].compareTo(array[minIndex])) < 0)
{      

27.                   
minIndex =
j;      

28.               
}      

29.           
}      

30.     

31.           
//先前只是记录最小元素索引,当最小元素索引确定后,再与每轮的第一个元素交换      

32.           
swap(array, i,
minIndex);      

33.       
}      

34.   
}      

35.       

36.    public
static void swap(Integer[] intgArr,int x,int
y){   

37.       
//Integer temp;
//这个也行   

38.       
int temp;   

39.       
temp=intgArr[x];   

40.       
intgArr[x]=intgArr[y];   

41.       
intgArr[y]=temp;   

42.   
}   

43.       

44.   
     

48.    public
static void main(String[] args)
{      

49.       
Integer[] intgArr = { 5, 9, 1, 4, 2, 6, 3, 8, 0, 7
};      

50.       
SelectSort insertSort = new
SelectSort();   

51.       
insertSort.select(intgArr);   

52.       
for(Integer
intObj:intgArr){   

53.           
System.out.print(intObj + "
");   

54.       
}     

55.           

56.   
}      

57.}      
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: