Will different arrays sync after bubble sorting one?

66 views Asked by At

As a school assignment, I have to create a Python app that allows the user to add personal information on X amount of people. With that said, the program allows the user to select many options and one of them is to sort the list of people with their infos alphabetically WITHOUT the use of sort() or quicksort() function whatsoever. The only thing left for me to do is to use the bubble sorting method.

Initially, I had the idea to create arrays for different data types like for example:

Last_names = [ ]

First_names = [ ]

Date_of_birth = [ ]

Gender = [ ]

but the thing is, if I apply bubble sort to Last_names, how would the other arrays info sync with the new order? Like are the infos on each person going to be mixed up?

Update:

so I decided to go with the format person1 = ["name1", "date_of_birth1", "gender1".....]

and then add that to another list

addressbook = ["person1", "person2", "person3", .....]

1

There are 1 answers

1
Niko B On

Instead of a list for each person I would used a dictionary. For example :

person1 = {
    "name":"Bao Tang",
    "date_of_birth":"2000/01/01",
    "gender":"male"
}

You can store the dictionaries directly into a list :

persons = [
    {
        "name":"Bao Tang",
        "date_of_birth":"2000/01/01",
        "gender":"male"
    },
    {
        "name":"Name 2",
        "date_of_birth":"2001/02/03",
        "gender":"female"
    }
]

Record and their info can then be accessed this way :

persons[index]["name"]
persons[index]["date_of_birth"]
persons[index]["gender"]

persons[0]["gender"] # based on the example list above, would return the value "male"

For your sorting you can add a "key" parameter to your function and use that parameter to specify on which info you want to sort :

def bubble_sort(arr, key):
    n = len(arr)
    for i in range(n - 1):
        for j in range(0, n - i - 1):
            if arr[j][key] > arr[j + 1][key]:            # we compare keys of 2 records
                arr[j], arr[j + 1] = arr[j + 1], arr[j]  # we swap the whole record

# example call
bubble_sort(persons, "date_of_birth")

Note : Even if it is pretty simple and should work this is all untested code. Use with caution !