Home > database >  longhand bubble sort of 2d array python problem
longhand bubble sort of 2d array python problem

Time:03-22

I have an array which i took from a text file, within the array is:

[('Sammy', '[email protected]', '72'), ('John', '[email protected]', '33'), ('Felix', '[email protected]', '89'), ('Henry', '[email protected]', '23'), ('Steven', '[email protected]', '83'), ('Harry', '[email protected]', '46'), ('Billy', '[email protected]', '62'), ('Alex', '[email protected]', '66'), ('Finn', '[email protected]', '49')]

within this 2d array i want to sort the data with those with the highest score at the top of a list and those with the lowest score at the bottom of the list. the list is called sorted_database and is below

my unworking code for the bubble sort is as follows (also i want to do it long hand without using any function e.g .sort):

swapped_database = []
def sortdata():
  swapped = True
  length = len(database)
  print(length)
  temp = 0
  while swapped == True:
    swapped = False

    for index in range(0,length -1,3):
      print(index)
      if database[index] > database[index 1]:
        temp = database[index]
        database[index] = database[index 1]
        database[index   1] = temp
        swapped = True
  swapped_database.append(database)
  print(swapped_database)
sortdata()

thanks in advance

CodePudding user response:

There are the following issues:

  • The inner loop should not make steps of 3. The tuple size is unrelated to the index at which that tuple resides in the database list. A database[index] value is a tuple, not a member of a tuple.

  • The comparison should be made on the score. This means you should explicitly compare the third element of the tuples, and convert them to number -- as they are strings.

  • swapped_database has no role to play here. Bubble sort is an inplace sorting algorithm, so it makes database itself sorted. Moreover, swapped_database.append(database) makes little sense. It makes database an entry inside swapped_database

Some other remarks on the code:

  • Avoid mutating global variables, so pass database as argument to your function.

  • In Python, you don't need a temp variable to swap values. Use tuple assignment instead.

  • while swapped == True is overkill, as swapped is already a boolean value, so just do while swapped

def sortdata(database):
  swapped = True
  length = len(database)
  while swapped == True:
    swapped = False
    for index in range(0,length -1):
      if int(database[index][2]) < int(database[index 1][2]):
        database[index], database[index 1] = database[index 1], database[index]
        swapped = True

Example use:

sortdata(database)
for entry in database:
    print(entry)

CodePudding user response:

This approach looks overly complicated with the swapped boolean and the step by 3. You can simply use a double for loop instead.

Here's a working implementation that returns the sorted list. It uses two for loops for swapping, and compares values based on the integer value of the third element in each tuple (rather than doing direct tuple comparison):

def sortdata(database):
  for iter_idx in range(len(database)):
      for elem_idx in range(len(database) - iter_idx - 1):
          if int(database[elem_idx][2]) > int(database[elem_idx   1][2]):
              database[elem_idx], database[elem_idx   1] = \
                  database[elem_idx   1], database[elem_idx]
  return database

With the sample data, calling print(sortdata(database)) outputs:

[[('John', '[email protected]', '33'),
 ('Sammy', '[email protected]', '72'),
 ('Felix', '[email protected]', '89'),
 ('Henry', '[email protected]', '23'),
 ('Steven', '[email protected]', '83'),
 ('Harry', '[email protected]', '46'),
 ('Billy', '[email protected]', '62'),
 ('Alex', '[email protected]', '66'),
 ('Finn', '[email protected]', '49')]]

Make sure that you pass database in as a parameter to the function. The upper bound to the second for loop is iter_idx as a suggested optimization by Mushroomator.

  • Related