Home Backend Development Python Tutorial Sorting Algorithms in Python

Sorting Algorithms in Python

Aug 27, 2024 am 06:03 AM

Sorting Algorithms in Python

What is Sorting?

Sorting refers to the process of arranging data in a specific order, typically in ascending or descending order, based on a linear relationship among the data items.

Why Do We Need Sorting?

Sorting is crucial when working with structured data because it allows for efficient data retrieval, simplifies data analysis, and enhances overall data management.

Sorting Algorithms

This post covers the following sorting algorithms: Bubble Sort, Selection Sort, Insertion Sort, Merge Sort, and Quick Sort.

Bubble Sort

Bubble Sort repeatedly steps through the array, comparing adjacent elements and swapping them if they are in the wrong order. This process continues until the array is sorted, with larger elements "bubbling" to the end.

Algorithm

Step 1: Begin
Step 2: i = 0
Step 3: if i < length(array) - 1, goto Step 4; else goto Step 10
Step 4: j = 0
Step 5: if j < length(array) - i - 1, goto Step 6; else goto Step 3
Step 6: if array[j] > array[j + 1], goto Step 7; else goto Step 8
Step 7: Swap array[j] and array[j + 1]
Step 8: increment j; goto Step 5
Step 9: increment i; goto Step 3
Step 10: End

Code

def bubble_sort(arr):
    print("Array Before Sorting: ", end='')
    print(arr)
    for i in range(len(arr)):
        for j in range(len(arr)-i-1):
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]

    print("Array After Sorting: ", end='')
    print(arr)

# Main
bubble_sort([7, 4, 1, 3, 4, 7, 87, 9, 6, 4, 2, 2, 3, 5, 6])

Time Complexity

Best Case : O(n)
Average Case : O(n^2)
Worst Case : O(n^2)

Selection Sort

Selection Sort finds the smallest value in the unsorted portion of the array and places it at the beginning of that portion.

Algorithm

Step 1 : Begin
Step 2 : i = 0
Step 3 : if i < length(array) - 1, goto Step 4; else goto Step 10
Step 4 : minimum_value = i; j = i + 1
Step 5 : if j < length(array), goto Step 6; else goto Step 9
Step 6 : if array[minimum_value] > array[j], goto Step 7; else goto Step 8
Step 7 : minimum_value = j
Step 8 : increment j; goto Step 5
Step 9 : swap array[minimum_value] and array[i]
Step 10 : increment i; goto Step 3
Step 11 : End

Code

def selection_sort(arr):
    print("Array Before Sorting: ", end='')
    print(arr)
    for i in range(len(arr) - 1):
        min_val = i
        for j in range(i + 1, len(arr)):
            if arr[j] < arr[min_val]:
                min_val = j

        arr[i], arr[min_val] = arr[min_val], arr[i]

    print("Array After Sorting: ", end='')
    print(arr)

# Main
selection_sort([7, 4, 1, 3, 4, 7, 87, 9, 6, 4, 2, 2, 3, 5, 6])

Time Complexity

Best Case : O(n^2)
Average Case : O(n^2)
Worst Case : O(n^2)

Insertion Sort

Insertion Sort builds the sorted array one element at a time by taking each element from the unsorted portion and inserting it into the correct position in the sorted portion.

Algorithm

Step 1: Begin
Step 2: i = 1
Step 3: if i < len(arr), goto Step 4; else goto Step 12
Step 4: key = arr[i]
Step 5: j = i - 1
Step 6: if j >= 0 and arr[j] > key, goto Step 7; else goto Step 10
Step 7: arr[j + 1] = arr[j]
Step 8: decrement j by 1
Step 9: goto Step 6
Step 10: arr[j + 1] = key
Step 11: increment i by 1; goto Step 3
Step 12: End

Code

def insertion_sort(arr):
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1

        while j >= 0 and arr[j] > key:
            arr[j + 1] = arr[j]
            j -= 1

        arr[j + 1] = key

# Main
arr = [7, 4, 1, 3, 4, 7, 87, 9, 6, 4, 2, 2, 3, 5, 6]
print("Array Before Sorting:", arr)
insertion_sort(arr)
print("Array After Sorting:", arr)

Time Complexity

Best Case : O(n)
Average Case : O(n^2)
Worst Case : O(n^2)

Merge Sort

Merge Sort is a divide-and-conquer algorithm that recursively divides the array into smaller sub-arrays, sorts them, and then merges them back together.

Algorithm

Merge Sort Algorithm

Step 1: Begin
Step 2: If length(array) <= 1, Return array; goto Step 9
Step 3: mid_point = length(array) // 2
Step 4: left_half = array[:mid_point]
Step 5: right_half = array[mid_point:]
Step 6: sorted_left = merge_sort(left_half)
Step 7: sorted_right = merge_sort(right_half)
Step 8: return merge(sorted_left, sorted_right)
Step 9: End

Merge Function

Step 1: Begin
Step 2: sorted_merge = []
Step 3: l = 0, r = 0
Step 4: if l < len(left) and r < len(right), goto Step 5; else goto Step 9
Step 5: if left[l] <= right[r], goto Step 6; else goto Step 7
Step 6: add left[l] to sorted_merge; increment l by 1
Step 7: add right[r] to sorted_merge; increment r by 1
Step 8: goto Step 4
Step 9: if l < len(left), goto Step 10; else goto Step 12
Step 10: add left[l] to sorted_merge; increment l by 1
Step 11: goto Step 9
Step 12: if r < len(right), goto Step 13; else goto Step 15
Step 13: add right[r] to sorted_merge; increment r by 1
Step 14: goto Step 12
Step 15: Return sorted_merge
Step 16: End

Code

def merge(left, right):
    sorted_merge = []
    l = r = 0
    while l < len(left) and r < len(right):
        if left[l] <= right[r]:
            sorted_merge.append(left[l])
            l += 1
        else:
            sorted_merge.append(right[r])
            r += 1

    while l < len(left):
        sorted_merge.append(left[l])
        l += 1

    while r < len(right):
        sorted_merge.append(right[r])
        r += 1

    return sorted_merge

def merge_sort(arr):
    if len(arr) <= 1:
        return arr

    mid_point = len(arr) // 2
    left_half = arr[:mid_point]
    right_half = arr[mid_point:]

    sorted_left = merge_sort(left_half)
    sorted_right = merge_sort(right_half)

    return merge(sorted_left, sorted_right)

# Main
arr = [7, 4, 1, 3, 4, 7, 87, 9, 6, 4, 2, 2, 3, 5, 6]
print("Array Before Sorting:", arr)
arr = merge_sort(arr)
print("Array After Sorting:", arr)

Time Complexity

Best Case : O(n log n)
Average Case : O(n log n)
Worst Case : O(n log n)

Quick Sort

Quick Sort is an efficient, in-place sorting algorithm that uses a divide-and-conquer approach. It selects a pivot element and partitions the array around the pivot so that elements less than the pivot are on its left and elements greater than the pivot are on its right. This process is then recursively applied to the sub-arrays.

Algorithm

Quick Sort

Step 1: Begin
Step 2: If low < high, goto Step 3; else goto Step 6
Step 3: pivot_index = partition(arr, low, high)
Step 4: quicksort(arr, low, pivot_index - 1)
Step 5: quicksort(arr, pivot_index + 1, high)
Step 6: End

Partition Function

Step 1: Begin
Step 2: pivot = arr[high]
Step 3: left = low, right = high - 1
Step 4: if left <= right goto Step 5, else goto Step 9
Step 5: if arr[left] > pivot and arr[right] < pivot, swap arr[left] and arr[right]
Step 6: if arr[left] <= pivot, increment left
Step 7: if arr[right] >= pivot, decrement right
Step 8: goto Step 4
Step 9: swap arr[left] and arr[high]
Step 10: return left
Step 11: End

Code

def partition(arr, low, high):
    pivot = arr[high]
    left = low
    right = high - 1
    while left <= right:
        if arr[left] > pivot and arr[right] < pivot:
            arr[left], arr[right] = arr[right], arr[left]
        if arr[left] <= pivot:
            left += 1
        if arr[right] >= pivot:
            right -= 1
    arr[left], arr[high] = arr[high], arr[left]
    return left

def quicksort(arr, low, high):
    if low < high:
        pivot_index = partition(arr, low, high)
        quicksort(arr, low, pivot_index - 1)
        quicksort(arr, pivot_index + 1, high)

# Main
arr = [7, 4, 1, 3, 4, 7, 87, 9, 6, 4, 2, 2, 3, 5, 6]
print("Array Before Sorting:", arr)
quicksort(arr, 0, len(arr) - 1)
print("Array After Sorting:", arr)

Time Complexity

Best Case : O(n log n)
Average Case : O(n log n)
Worst Case : O(n^2)

The above is the detailed content of Sorting Algorithms in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SQLAlchemy 2.0 Deprecation Warning and Connection Close Problem Resolving Guide SQLAlchemy 2.0 Deprecation Warning and Connection Close Problem Resolving Guide Aug 05, 2025 pm 07:57 PM

This article aims to help SQLAlchemy beginners resolve the "RemovedIn20Warning" warning encountered when using create_engine and the subsequent "ResourceClosedError" connection closing error. The article will explain the cause of this warning in detail and provide specific steps and code examples to eliminate the warning and fix connection issues to ensure that you can query and operate the database smoothly.

How to automate data entry from Excel to a web form with Python? How to automate data entry from Excel to a web form with Python? Aug 12, 2025 am 02:39 AM

The method of filling Excel data into web forms using Python is: first use pandas to read Excel data, and then use Selenium to control the browser to automatically fill and submit the form; the specific steps include installing pandas, openpyxl and Selenium libraries, downloading the corresponding browser driver, using pandas to read Name, Email, Phone and other fields in the data.xlsx file, launching the browser through Selenium to open the target web page, locate the form elements and fill in the data line by line, using WebDriverWait to process dynamic loading content, add exception processing and delay to ensure stability, and finally submit the form and process all data lines in a loop.

python pandas styling dataframe example python pandas styling dataframe example Aug 04, 2025 pm 01:43 PM

Using PandasStyling in JupyterNotebook can achieve the beautiful display of DataFrame. 1. Use highlight_max and highlight_min to highlight the maximum value (green) and minimum value (red) of each column; 2. Add gradient background color (such as Blues or Reds) to the numeric column through background_gradient to visually display the data size; 3. Custom function color_score combined with applymap to set text colors for different fractional intervals (≥90 green, 80~89 orange, 60~79 red,

How to create a virtual environment in Python How to create a virtual environment in Python Aug 05, 2025 pm 01:05 PM

To create a Python virtual environment, you can use the venv module. The steps are: 1. Enter the project directory to execute the python-mvenvenv environment to create the environment; 2. Use sourceenv/bin/activate to Mac/Linux and env\Scripts\activate to Windows; 3. Use the pipinstall installation package, pipfreeze>requirements.txt to export dependencies; 4. Be careful to avoid submitting the virtual environment to Git, and confirm that it is in the correct environment during installation. Virtual environments can isolate project dependencies to prevent conflicts, especially suitable for multi-project development, and editors such as PyCharm or VSCode are also

How to implement a stack data structure using a list in Python? How to implement a stack data structure using a list in Python? Aug 03, 2025 am 06:45 AM

PythonlistScani ImplementationAking append () Penouspop () Popopoperations.1.UseAppend () Two -Belief StotetopoftHestack.2.UseP OP () ToremoveAndreturnthetop element, EnsuringTocheckiftHestackisnotemptoavoidindexError.3.Pekattehatopelementwithstack [-1] on

python schedule library example python schedule library example Aug 04, 2025 am 10:33 AM

Use the Pythonschedule library to easily implement timing tasks. First, install the library through pipinstallschedule, then import the schedule and time modules, define the functions that need to be executed regularly, then use schedule.every() to set the time interval and bind the task function. Finally, call schedule.run_pending() and time.sleep(1) in a while loop to continuously run the task; for example, if you execute a task every 10 seconds, you can write it as schedule.every(10).seconds.do(job), which supports scheduling by minutes, hours, days, weeks, etc., and you can also specify specific tasks.

How to handle large datasets in Python that don't fit into memory? How to handle large datasets in Python that don't fit into memory? Aug 14, 2025 pm 01:00 PM

When processing large data sets that exceed memory in Python, they cannot be loaded into RAM at one time. Instead, strategies such as chunking processing, disk storage or streaming should be adopted; CSV files can be read in chunks through Pandas' chunksize parameters and processed block by block. Dask can be used to realize parallelization and task scheduling similar to Pandas syntax to support large memory data operations. Write generator functions to read text files line by line to reduce memory usage. Use Parquet columnar storage format combined with PyArrow to efficiently read specific columns or row groups. Use NumPy's memmap to memory map large numerical arrays to access data fragments on demand, or store data in lightweight data such as SQLite or DuckDB.

python logging to file example python logging to file example Aug 04, 2025 pm 01:37 PM

Python's logging module can write logs to files through FileHandler. First, call the basicConfig configuration file processor and format, such as setting the level to INFO, using FileHandler to write app.log; secondly, add StreamHandler to achieve output to the console at the same time; Advanced scenarios can use TimedRotatingFileHandler to divide logs by time, for example, setting when='midnight' to generate new files every day and keep 7 days of backup, and make sure that the log directory exists; it is recommended to use getLogger(__name__) to create named loggers, and produce

See all articles