Bubble Sort sorting algorithm of the basic Python3, insertion sort, selection sort

  Basic sorting algorithm complexity classification by time

  O (n ^ 2)

  Bubble Sort

  Insertion Sort

  Selection Sort

  Q(n log n)

  Divide and rule

  Quick Sort

  Merge sort

  Bubble Sort

  Comparison of two adjacent elements, after a large number of pushing, after a traverse the entire list, the entry to the maximum bubbling end of the list are arranged to i.

  Lite bubble sort following examples

  def bubble(sl):

  """

  Bubble sort, O (n ^ 2)

  Comparison of two adjacent elements, a large push, after a traverse the entire list, the items are arranged in the maximum bubbling manner to the end of the list

  :param sl: list

  :return:

  """

  for i in range(len(sl)-1):

  for j in range(i+1, len(sl)):

  if sl[i] > sl[j]:

  sl[i], sl[j] = sl[j], sl[i]

  return sl

  The following exemplary optimized version of bubble sort

  def bubble_sort(items):

  """

  Bubble sort, or change the while loop is more accustomed to the for loop

  Preferably O (n)

  Worst O (n ^ 2)

  """

  items_len = len (items)

  for i in range(1, items_len):

  has_swap = False

  for j in range(1, items_len):

  if items[j - 1] > items[j]:

  has_swap = True

  items[j - 1], items[j] = items[j], items[j - 1]

  if not has_swap:

  break

  return items

  Insertion Sort

  The second number corresponds to the order from the front to start looking for a position, as an insert to the same sequence of playing cards in good order.

  def insert_sort_for(items):

  """

  Insertion sort, for loop, while loop intermediate or easy to understand:

  Larger than the value of the number of inserted Norway, do not need to move up until it is the inserted location.

  : param items:  Wuxi gynecological check how much money http://www.csyhjlyy.com/

  :return:

  """

  for i in range(1, len(items)):

  item_insert = items[i]

  j = i - 1

  while j >= 0:

  if item_insert < items[j]:

  items [j + 1] = items [j] # is larger than the value of the element is inserted, a rearward movement

  j -= 1

  else: # is not required to move out of the loop

  break

  items [j + 1] = item_insert # inserted location found

  return items

  Selection Sort

  Search the entire list, find the smallest item location, list each item will determine its position is the smallest items.

  def select_sort(items):

  """

  Select sorting, searching the entire list, find the smallest item location

  """

  for i in range(len(items)-1):

  min_index = i

  for j in range(i+1, len(items)):

  if items[j] < items[min_index]:

  min_index = j

  if min_index != i:

  items[min_index], items[i] = items[i], items[min_index]

  return items


Guess you like

Origin blog.51cto.com/14335413/2429073