public class MaxnumNofM{ public static int[] MaxnumNofM(int BigArr[], int N ){ //取原始数组的前N个元素 int[] ResArr = new int[N]; for(int i=0; i<N;i++){ ResArr[i] = BigArr[i]; } //标记上一轮是否发生过交换 boolean bExchanged = true; //遍历后续的元素 for(int i = N; i < BigArr.length; ++i){ int idx = 0; //如果上一轮发生过交换 if( bExchanged ){ //找出ResArr中最小的元素 for( int j = 1; j < N; ++j ){ if( ResArr[idx] > ResArr[j] ) idx = j; } } //这个后续元素比ResArr中最小的元素大,则替换。 if( BigArr[i] > ResArr[idx] ){ bExchanged = true; ResArr[idx] = BigArr[i]; } else bExchanged = false; } return ResArr; } public static void main(String[] args) { int[] strArr = {6,5,12,59,87,36,2,8,4,96,31,656,964,41,233,978,456,14,978}; int[] deetArr = MaxnumNofM(strArr,5); for(int i:deetArr) System.out.print(i+" "); } }
时间: 2024-09-30 16:02:28