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

本文详细介绍了选择排序的基本思想和排序过程,并通过一个具体的示例来展示如何进行选择排序。此外,还提供了一段Java代码实现,帮助读者更好地理解选择排序算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二、选择排序

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.}      

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值