Selection Sort Algorithm-选择排序算法


Selection Sort is a simple sorting algorithm that find the smallest

element in the array and swaps it with the element in the first position,

then find the second smallest element in and swaps it with the element in

the second position,and continues in this way until the entire array

is sorted.  


The algorithm is efficient for smaller lists,but very inefficient for

larger lists,Also,it does not require any additional storage space,as

it operate in-place.  


for example:

 the array is [4,1,5,2]

 step 1: [1,4,5,2] swap 4,1,because 1 is the smallest

 step 2: [1,2,5,4] swap 4,2 because 2 is the second smallest

 step 3: [1,2,4,5] swap 5,4 because 4 is the third smallest  


public void sortElement(int[] elements) {
    int length =elements.length;
    for (int i=0;i<length-1;i++){ //最后一个元素后面没有数据了,所以没必要包含在循环体内
        int ele=elements[i];
        int swapIndex=-1;
        boolean swap=false;
        for (int j=i+1;j<length;j++){
            System.out.println("jvalue = " + j+"---"+ele);
            if(ele>elements[j]){ // save the smaller value and index
                swap=true ;
        if(swap&&swapIndex>-1){  // swap the values
            int temp=elements[i];


  • 最新评论
  • 总共0条评论
  • Powered by bjyblog modified by Adam © 2014-2022 版权所有 ICP证:鲁ICP备15039297号
  • 联系邮箱