代码改变世界

对数组去重排序

2017-12-14 20:19  hdwen  阅读(896)  评论(0编辑  收藏  举报
/**
 * FileName: TestPractiseDuplicateArray
 * Author:   HDWEN
 * Date:     2017/12/14 15:49
 * Description: 将数组中重复元素删除,并按照一定顺序排序
 * Desc:
 */
package cn.hdwen.java.testarray;

import java.util.Arrays;

public class TestPractiseDuplicateArray {
    public static void main(String args[]) {
        int n = 20;
        Object[] arr = new Object[n];
        //随机产生0-20的随机数
        for (int i = 0; i < n; i++) {
            arr[i] = (int) (Math.random() * n);
        }
        System.out.println("初始化数组为:" + Arrays.toString(arr));
        ifRepeat(arr);
    }

    public static void ifRepeat(Object[] arr) {
        Object[] tempArr = new Object[arr.length];
        int t = 0;
        for (int i = 0; i < arr.length; i++) {
            boolean isTrue = true;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] == arr[j]) {
                    isTrue = false;
                    break;
                }
            }
            if (isTrue) {
                tempArr[t] = arr[i];
                t++;
            }
        }
        Object[] newArr = new Object[t];
        System.arraycopy(tempArr, 0, newArr, 0, t);
        System.out.println("去重后的数组:" + Arrays.toString(newArr));
        //对newArr排序:首先将Object对象转化为int,前提我是知道int基本类型的
        int con;
        int[] newSortArr = new int[newArr.length];
        for (int x = 0; x < newSortArr.length; x++) {
            newSortArr[x] = (int) newArr[x];
        }
        //进行排序从小到大
        for (int i = 0; i < newSortArr.length; i++) {
            for (int j = i + 1; j < newSortArr.length; j++) {
                if (newSortArr[i] > newSortArr[j]) {
                    con = newSortArr[j];
                    newSortArr[j] = newSortArr[i];
                    newSortArr[i] = con;
                }
            }
        }
        System.out.println("排序后的数组:" + Arrays.toString(newSortArr));
    }
}