Packagearithmetic;Importjava.util.Arrays;/*** Find the maximum number of k elements in an array sequentially@authorSHI*/ Public classFindmaxfigure { Public Static voidMain (string[] args) {int[] A=New int[]{1,5,-1,8,0,2}; System.out.println (Arrays.tostring (Findbigfigure (A,3))); } /*** Idea: After finding the largest element, store it in the front of the array until the K is satisfied *@parama primitive array *@paramK *@return */ Public Static int[] Findbigfigure (int[] A,intk) {int[] temp =New int[K]; intm = 0; intindex = 0; for(; index < k; index++) { intmax = A[index];//Suppose an element in an array is the largest (in this case each loop sequentially, the index of the array element obtained is 0,1,2 ...) intFlag = 0; for(intj = index+1; J < A.length; J + +) { if(Max <A[j]) {Max=A[j]; Flag= J;//Save the index of the largest number found } } //swap the largest number to the front of the array in turn intt =A[index]; A[index]=A[flag]; A[flag]=T; //Save the found number in the arraytemp[m++] =Max; } returntemp; } }
Algorithm title: Find the largest number of K elements in an array, sequentially