Quicksort in Python

by atalaykutlay

An easy quicksort implementation in Python.

Quicksort in Python
1def qsort(items):
2    if not items:
3        return []
4    else:
5        pivot = items[0]
6        less = [x for x in items if x <  pivot]
7        more = [x for x in items[1:] if x >= pivot]
8        return qsort(less) + [pivot] + qsort(more)

✨ Code Explanation ✨

This code implements the quicksort algorithm, which is a sorting algorithm that sorts a list by dividing it into smaller sub-lists based on a pivot element, and recursively sorting the sub-lists. The function takes an unsorted list as an input, and checks if it is empty. If it is empty, the function returns an empty list. If the list is not empty, the function selects the first element of the list as the pivot, and creates two new lists - one containing all the elements that are less than the pivot, and another containing all the elements that are greater than or equal to the pivot. The function then recursively calls itself on the two new lists, and concatenates the sorted less list, the pivot element, and the sorted more list into a single sorted list. This process continues until the entire list is sorted.

Share

Share
Video
A cool 10 sec video.
Share
Detailed
Title, description, and syntax highlighted code.
Share
Simple
Syntax highlighted code with gradient background colored presentation.

Comments

It looks like there is no comment for this snippet. Leave the first one!
You need to login to send a comment.

Similar Snippets

Count Number of Texts
Count Number of Texts

Solution to "Count Number of Texts" question on Leetcode.

Language: python17 months ago
Second Minimum Node In a Binary Tree
Second Minimum Node In a Binary Tree

Solution to "Second Minimum Node In a Binary Tree" on Leetcode.

Language: python16 months ago
Combination Sum
Combination Sum

Solution for the Combination Sum problem on Leetcode.

Language: python18 months ago