如何在冒泡排序算法中避免重复的字符串值?

huangapple go评论74阅读模式
英文:

How to avoid duplicate string values in a bubble sort algorithm?

问题

我正在努力解决如何在我的排序算法中避免打印重复的名称

我忽略空字符串的原因是,我正在实现的系统是一个票务预订系统,它只显示名称列表,而不显示空的时间段。

有人可以帮帮我吗?

String[] name = {"fiona", "vacant", "allen", "fiona", "david", "vacant", "vacant"};
for (int i = 0; i <= (name.length - 1); i++) {
    for (int j = i + 1; j < name.length; j++) {
        if (name[i].compareTo(name[j]) > 0) {
            String temp = name[i];
            name[i] = name[j];
            name[j] = temp;
        }
    }
    if (!name[i].equals("vacant")) {
        System.out.println(name[i] + " ");
    }
}
英文:

I'm trying to figure out on how can i avoid printing duplicate names in my sorting algorithm.

The reason i'm ignoring the vacant string is that the system i'm implementing, is a ticket booking system which displays a list of only names instead of the vacant slots.

Can some help me please ?

String[] name={&quot;fiona&quot;,&quot;vacant&quot;,&quot;allen&quot;,&quot;fiona&quot;,&quot;david&quot;,&quot;vacant&quot;,&quot;vacant&quot;};
        for (int i = 0; i &lt;= (name.length-1); i++){
            for (int j = i+1; j &lt; name.length; j++ ){
                if (name[i].compareTo(name[j])&gt;0) {
                    String temp = name[i];
                    name[i] = name[j];
                    name[j] = temp;
                }
            }
            if (!name[i].equals(&quot;vacant&quot;)) {
                System.out.println(name[i] + &quot; &quot;);
            }
        }

</details>


# 答案1
**得分**: 1

只需检查打印的名称是否与先前的名称相同:

```java
String[] name = {"fiona", "vacant", "allen", "fiona", "david", "vacant", "vacant"};
for (int i = 0; i <= (name.length - 1); i++) {
    for (int j = i + 1; j < name.length; j++) {
        if (name[i].compareTo(name[j]) > 0) {
            String temp = name[i];
            name[i] = name[j];
            name[j] = temp;
        }
    }
    if (!name[i].equals("vacant") && (i == 0 || !name[i - 1].equals(name[i]))) {
        System.out.println(name[i] + " ");
    }
}
英文:

Just check if the name you are printing is the same as the previous one:

String[] name={&quot;fiona&quot;,&quot;vacant&quot;,&quot;allen&quot;,&quot;fiona&quot;,&quot;david&quot;,&quot;vacant&quot;,&quot;vacant&quot;};
for (int i = 0; i &lt;= (name.length-1); i++){
    for (int j = i+1; j &lt; name.length; j++ ){
        if (name[i].compareTo(name[j])&gt;0) {
            String temp = name[i];
            name[i] = name[j];
            name[j] = temp;
        }
    }
    if (!name[i].equals(&quot;vacant&quot;) &amp;&amp; (i == 0 || !name[i-1].equals(name[i]))) {
        System.out.println(name[i] + &quot; &quot;);
    }
}

huangapple
  • 本文由 发表于 2020年3月17日 01:23:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/60710471.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定