Title

每日作业

删除重复值

有一个整数数组, 去掉该数组中重复元素后排序打印, 

(相同的数字只保留一个, 禁止使用set和语言本身提供的函数)

输入: 

第一行: 整数N  表示该数组的长度

第二行: 数组中每个元素的值An

(0<N<10000, 0<An<1000)

输出:

去掉重复元素后的有序数组

样例输入:

11

1 3 4 2 6 2 6 2 8 2 6

样例输出:

1 2 3 4 6 8

 1 package com.work;
 2 
 3 import java.util.*;
 4 
 5 /**
 6  * @author My
 7  */
 8 public class Assignment_15 extends QuickSort{
 9     public static void main(String[] args) {
10 //        Set A = new HashSet();   //set方法
11         Scanner reading = new Scanner(System.in);
12         System.out.println("输入数组的长度:");
13         int n = reading.nextInt();
14         System.out.println("输入数组中每个元素的值:");
15         int[] num = new int[n];
16         for (int i = 0; i < n; i++) {
17             num[i] = reading.nextInt();
18 //            A.add(num[i]);
19         }
20         if (n < 0){
21             System.out.println("输入过小,请重新输入!");
22             n = reading.nextInt();
23         }
24 //        Iterator it = A.iterator();
25 //        while (it.hasNext()) {
26 //            System.out.print(it.next()+" ");
27 //        }
28 //        Arrays.sort(num); //调用排序
29         QuickSort sort = new QuickSort();
30         sort.quickSort(num,0,n-1);
31         System.out.println("去掉重复元素后的有序数组:");
32         System.out.print(num[0]+" ");
33         for (int i = 1; i < n; i++) {
34             if (num[i]==num[i-1]){
35                 continue;
36             }else {
37                 System.out.print(num[i]+" ");
38             }
39         }
40     }
41 }
42 class QuickSort {    //快速排序
43     public void quickSort(int[] arr, int low, int high) {
44 
45         if (low < high) {
46             // 找寻基准数据的正确索引
47             int index = getIndex(arr, low, high);
48 
49             // 进行迭代对index之前和之后的数组进行相同的操作使整个数组变成有序
50             quickSort(arr, low, index - 1);
51             quickSort(arr, index + 1, high);
52         }
53 
54     }
55 
56     private int getIndex(int[] arr, int low, int high) {
57         // 基准数据
58         int tmp = arr[low];
59         while (low < high) {
60             // 当队尾的元素大于等于基准数据时,向前挪动high指针
61             while (low < high && arr[high] >= tmp) {
62                 high--;
63             }
64             // 如果队尾元素小于tmp了,需要将其赋值给low
65             arr[low] = arr[high];
66             // 当队首元素小于等于tmp时,向前挪动low指针
67             while (low < high && arr[low] <= tmp) {
68                 low++;
69             }
70             // 当队首元素大于tmp时,需要将其赋值给high
71             arr[high] = arr[low];
72 
73         }
74         // 跳出循环时low和high相等,此时的low或high就是tmp的正确索引位置
75         // 由原理部分可以很清楚的知道low位置的值并不是tmp,所以需要将tmp赋值给arr[low]
76         arr[low] = tmp;
77         return low; // 返回tmp的正确位置
78     }
79 }

 

posted @ 2020-12-11 17:19  WAASSTT  阅读(106)  评论(0)    收藏  举报
Title