public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入十个数:");
int[] list = new int[10];
for (int i = 0; i < 10; i++) {
list[i] = scanner.nextInt();
}
System.out.println("原始数组为:" + Arrays.toString(list));
System.out.print("去除重复后的数组:" + Arrays.toString(removeDuplicate(list)));
int arr[]=removeDuplicate(list);
System.out.print("排序后的数组为:" + Arrays.toString(arraySort(arr)));
}
private static int[] arraySort(int[] list) {
int tmp;
//第一个for循环是比较次数,减一的就是最后一次(趟)不用循环
for (int i = 0; i < list.length - 1; i++) {
//第二个循环比较的是比较的次数 每次减一就是少比较一次
for (int j = 0; j < list.length - 1 - i; j++) {
if (list[j] > list[j + 1]) {
tmp = list[j + 1];
list[j + 1] = list[j];
list[j] = tmp;
}
}
}
return list;
}
private static int[] removeDuplicate(int[] list) {
int[] tmpList = new int[list.length];
int listLength = 0;
//遍历循环数组
for (int i = 0; i < list.length; i++) {
boolean isDuplicate = true;
//遍历循环数组
for (int j = i; j < list.length; j++) {
//1!=7 但数组值相等
if (i != j && list[i] == list[j]) {
isDuplicate = false;
break;
}
}
if (isDuplicate) {
tmpList[listLength] = list[i];
listLength++;
}
}
int[] newList = new int[listLength];
//源数组,源数组要复制的起始位置;,目的数组,目的数组放置的起始位置,复制的长度
System.arraycopy(tmpList, 0, newList, 0, listLength);
return newList;
}
数组去重,排序
最新推荐文章于 2021-07-07 09:58:44 发布