Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
703 views
in Technique[技术] by (71.8m points)

java - Sorting (names) using Merge Sort

having problem sorting repeated Strings,

and here's my code..

i successfully sorted the first array but in the second (with repeated strings) it seems not in orderly output, can you help me to trace whats wrong in my code..

import java.util.*;

public class NewClass {
    public static void main(String[] args) {
        String[] ClassOne = { "Kring", "Panda", "Soliel", "Darryl", "Chan", "Matang", "Jollibee.", "Inasal" };
        String[] ClassTwo = { "Minnie", "Kitty", "Madonna", "Miley", "Zoom-zoom", "Cristine", "Bubbles", "Ara", "Rose", "Maria" };
        String[] names = new String[ClassOne.length + ClassTwo.length];

        mergeSort(ClassOne);
        mergeSort(ClassTwo);

        merge(names, ClassOne, ClassTwo);

        mergeSort(names);
        //Arrays.sort(names);

        for (String ClassThree : names) {
            System.out.println(ClassThree);
        }
    }

    public static void mergeSort(String[] names) {
        if (names.length > 2) {
            String[] left = new String[names.length / 2];
            String[] right = new String[names.length - names.length / 2];

            for (int i = 0; i < left.length; i++) {
                left[i] = names[i];
            }

            for (int i = 0; i < right.length; i++) {
                right[i] = names[i + names.length / 2];
            }

            mergeSort(left);
            mergeSort(right);
            merge(names, left, right);
        }
    }

    public static void merge(String[] names, String[] left, String[] right) {
        int a = 0;
        int b = 0;
        for (int i = 0; i < names.length; i++) {
            if (b >= right.length || (a < left.length && left[a].compareToIgnoreCase(right[b]) < 0)) {
                names[i] = left[a];
                a++;
            } else {
                names[i] = right[b];
                b++;
            }
        }
    }
}

and heres the output::

Ara
Chan
Cristine
Bubbles
Jollibee.
Inasal
Kring
Madonna
Matang
Miley
Minnie
Kitty
Panda
Rose
Maria
Soliel
Darryl
Zoom-zoom

...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Change

if (names.length > 2) {

with

if (names.length >= 2) {

output

Ara
Bubbles
Chan
Cristine
Darryl
Inasal
Jollibee.
Kitty
Kring
Madonna
Maria
Matang
Miley
Minnie
Panda
Rose
Soliel
Zoom-zoom

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...