Home > OS >  How to apply Bubble Sort to the data stored in different Arrays
How to apply Bubble Sort to the data stored in different Arrays

Time:07-01

Can I sort this code below based on the number ?

Like if the data is sorted, let's say ascending it should look like:

001  Graciella
012  Steven
094  Marcellin

... and so on 

My code:

String [][] sis = new String [][] {
    {"001",  "980", "777", "169","094","233", "012"},
    {"Graciella","Martinus","Renata","Vianney","Marcellin", "Joakim", "Steven"}
};      

System.out.println(sis[0][0] " "  sis[1][0]);
System.out.println(sis[0][1] " "  sis[1][1]);
System.out.println(sis[0][2] " "  sis[1][2]);
System.out.println(sis[0][3] " "  sis[1][3]);
System.out.println(sis[0][4] " "  sis[1][4]);
System.out.println(sis[0][5] " "  sis[1][5]);
System.out.println(sis[0][6] " "  sis[1][6]);

I have tried the following, but I feel like I did something wrong. But I don't know what.

String num [] = {"001", "980", "777", "169", "094", "233", "012"};
int NUM [] = new int[num.length];
        
for (int i = 0; i < NUM.length;i  ) {
    NUM[i] = Integer.parseInt(num[i]);
}
        
String nem [] = {"Graciella","Martinus","Renata","Vianney","Marcellin", "Joakim", "Steven"};
        
        
for (int i = 0; i < 6; i  ) {
    for(int j = 0; j < 6; j  ) {
        if (num[j].compareTo(num[j 1]) > 0) {
            String temp = num[j];
            num[j] = num[j 1];
            num[j 1]= temp;
        }
    }
}
        
System.out.println();
        
for (int i = 0; i < 6; i  ) {
    for(int j = 0; j < 6; j  ) {
        if (nem[j].compareTo(nem[j 1]) > 0) {
            String temp = nem[j];
            nem[j] = nem[j 1];
            nem[j 1]= temp;
        }
    }
}

for (int j = 0; j < 6; j  ) {
    System.out.println(num[j]   " "   nem[j]);
}

Can you tell me what I'm doing wrong ? And can I sort this data based on the name?

CodePudding user response:

As @Elliott Frisch has pointed out in the comments, it would be way easier and cleaner if you treated these data as objects instead of keeping persons properties scattered among two different arrays, which make your solution brittle and unflexible.

That's how the Person class might look like:

public class Person {
    private int id;
    private String name;
    
    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }
    
    public int getId() {
        return id;
    }
    
    public String getName() {
        return name;
    }
    
    @Override
    public String toString() {
        return String.format("d %s", id, name);
    }
}

And that how we can implement bubble sort.

Note: there's no need to iterate through the hole array in the nested loop (condition j < 6) each time because i elements at the very end of the array are already sorted. The highest element from the unsorted part "bubbles up" at each iteration step and takes its place before the start of the sorted part.

Also, hard-coding values like in the condition j < 6 is a bad practice. Use method parameters, their attributes, static constants, etc., and not hard-coded values. Even if your logic would be flawless, it would already cause you troubles because you have 7 elements in each array, not 6.

public static void sortPeopleWithBubbleSort(Person[] people) {
    for (int i = 0; i < people.length; i  ) {
        for (int j = 0; j < people.length - 1 - i; j  ) {
            if (people[j].getId() > people[j   1].getId()) {
                Person temp = people[j   1];
                people[j   1] = people[j];
                people[j] = temp;
            }
        }
    }
}

main()

public static void main(String[] args) {
    Person[] people = new Person[]{
        new Person(1, "Graciella"),
        new Person(980, "Martinus"),
        new Person(777, "Renata"),
        new Person(169, "Vianney"),
        new Person(94, "Marcellin"),
        new Person(233, "Joakim"),
        new Person(12, "Steven")
    };
    // sorting
    sortPeopleWithBubbleSort(people);
    // printing
    for (Person person: people) {
        System.out.println(person);
    }
}

Output:

001 Graciella
012 Steven
094 Marcellin
169 Vianney
233 Joakim
777 Renata
980 Martinus

As @hfontanez suggested in the comments, we can make sortPeopleWithBubbleSort() method more flexible by providing and additional argument - Comparator (a special object which is used to compare object that has no natural order).

It might look like that:

// sorting by id
Comparator<Person> byId = Comparator.comparingInt(Person::getId);

sortPeopleWithBubbleSort(people, byId);
// sorting by name
Comparator<Person> byName = Comparator.comparing(Person::getName);

sortPeopleWithBubbleSort(people, byName);
public static void sortPeopleWithBubbleSort(Person[] people,
                                            Comparator<Person> comparator) {
    
    for (int i = 0; i < people.length; i  ) {
        for (int j = 0; j < people.length - 1 - i; j  ) {
            if (comparator.compare(people[j], people[j   1]) > 0) {
                Person temp = people[j   1];
                people[j   1] = people[j];
                people[j] = temp;
            }
        }
    }
}

To learn how to build comparators using Java-8 methods have a look at this post. And if you are not comfortable with Java 8 functional programming features, you it would be better to start with this tutorial.

CodePudding user response:

I added comments to the code for explaining. I did not include some best-code practices (i.e. do not duplicate code) I just focused on alghorithm.

Also easiest would be to first create new array that connects the two strings (number and name) together and then sort just this extra array. However I do not know if you need the original arrays sorted for other reasons, therefore I kept it as it is.

    for (int i = 0; i < 6; i  ) {
        for(int j = 0; j < 6; j  ) {
            if (num[j].compareTo(num[j 1]) > 0) {                   
                String temp = num[j];
                num[j] = num[j 1];
                num[j 1]= temp;

                // You need to switch this as well as you keep it as pair, so it has to be
                // in same position after shift

                temp = nem[j];
                nem[j] = nem[j 1];
                nem[j 1]= temp;
            }
        }
    }
    
    System.out.println();
    
    for (int i = 0; i < 6; i  ) {
        for(int j = 0; j < 6; j  ) {
            // only if the number is the same, then check which string has priority
            if (nim[j] == nim[j 1] && nem[j].compareTo(nem[j 1]) > 0) {
                String temp = nem[j];
                nem[j] = nem[j 1];
                nem[j 1]= temp;

                // You need to keep the other array in sync
                temp = num[j];
                num[j] = num[j 1];
                num[j 1]= temp;
            }
        }
    }
  • Related