- import java.util.Arrays;
- public class Test3 {
- public static void main(String[] args) {
- int[] arr = {23, 56, 29, 78, 77, 111, 12, 40}; //随机数组arr
-
- int[] indexArr = new int[arr.length]; //记录随机数组的元素索引
- int[] absArr = new int[arr.length]; //绝对值数组absArr
- int[] newArr = new int[arr.length]; //排序后的数组
-
- for (int i = 0; i < arr.length; i++) { //遍历原数组
- absArr[i] = Math.abs(arr[i] - 50); //得到绝对值数组
- indexArr[i] = i; //得到索引数组
- }
- //对absArr进行选择排序,先找到最大的元素(即找到离50最远的数),存到absArr[0],并把在arr中的索引也存到indexArr[0]
- for (int i = 0; i < absArr.length - 1; i++) {
-
- for (int j = i + 1; j < absArr.length; j++) {
- if (absArr[i] < absArr[j]) {
- int temp = absArr[i];
- absArr[i] = absArr[j];
- absArr[j] = temp;
- int index = indexArr[i];
- indexArr[i] = indexArr[j];
- indexArr[j] = index;
-
- }
-
- }
- }
-
- System.out.print(Arrays.toString(indexArr));
- for (int i = 0; i < indexArr.length; i++) {
- System.out.print(arr[indexArr[i]] + " ");
- }
-
- }
- }
复制代码
|