问题描述
publicclassSelectSort{publicstaticvoidmain(String[]args){double[]array=newdouble[]{12.3,15.2,15.8,16.3,147.52,266.2,1,2,3,54};selectionSort(array);for(doublevalue:array){System.out.println(value);}}publicstaticvoidselectionSort(double[]array){doublecurrentMax=array[0];intcurrentMaxIndex=0;for(inti=array.length-1;i>=1;i--){/**选择最大的数值*/for(intj=1;j<=i;j++){if(array[j]<currentMax){currentMax=array[j];currentMaxIndex=j;}}/**swap*/if(currentMaxIndex!=i){array[currentMaxIndex]=array[i];array[i]=currentMax;}}}}
解决方案
解决方案二:
publicstaticvoidselectionSort(double[]array){for(inti=array.length-1;i>=0;i--){doublecurrentMax=array[0];intcurrentMaxIndex=0;/**选择最大的数值*/for(intj=0;j<=i;j++){if(array[j]>currentMax){currentMax=array[j];currentMaxIndex=j;System.out.println(currentMaxIndex+"****"+currentMax);}}/**swap*/if(currentMaxIndex!=i){array[currentMaxIndex]=array[i];array[i]=currentMax;}}}
你的算法有问题,doublecurrentMax=array[0];intcurrentMaxIndex=0;要记得每遍历一次之后要重新赋值