Computer Science

Quicksort Python

Quicksort is a sorting algorithm that uses a divide-and-conquer approach to sort an array or list. In Python, the algorithm works by selecting a pivot element and partitioning the list into two sub-lists, one with elements smaller than the pivot and the other with elements larger than the pivot. The process is repeated recursively until the entire list is sorted.

Written by Perlego with AI-assistance

5 Key excerpts on "Quicksort Python"

  • Hands-On Data Structures and Algorithms with Python
    eBook - ePub

    Hands-On Data Structures and Algorithms with Python

    Write complex and powerful code using the latest features of Python 3.7, 2nd Edition

    • Dr. Basant Agarwal, Benjamin Baka(Authors)
    • 2018(Publication Date)
    • Packt Publishing
      (Publisher)
    In this chapter, we explored a number of important and popular sorting algorithms, which are very useful for many real-world applications. We discussed bubble sort, insertion sort, selection sort, quick sort, and heap sort algorithms, along with the explanation of their implementation in Python. Quick sort performs much better than the other sorting algorithms. Of all the algorithms discussed, quick sort preserves the index of the list that it sorts. We'll use this property in the next chapter as we explore the selection algorithms.
    In the next chapter, we will be discussing the concepts related to the selection strategy and algorithms.
  • Hands-On Data Structures and Algorithms with Python

    11

    Sorting

    Sorting means reorganizing data in such a way that it is in ascending or descending order. Sorting is one of the most important algorithms in computer science and is widely used in database-related algorithms. For several applications, if the data is sorted, it can efficiently be retrieved, for example, if it is a collection of names, telephone numbers, or items on a simple to-do list.
    In this chapter, we’ll study some of the most important and popular sorting techniques, including the following:
    • Bubble sort
    • Insertion sort
    • Selection sort
    • Quicksort
    • Timsort

    Technical requirements

    All source code used to explain the concepts of this chapter is provided in the GitHub repository at the following link: https://github.com/PacktPublishing/Hands-On-Data-Structures-and-Algorithms-with-Python-Third-Edition/tree/main/Chapter11

    Sorting algorithms

    Sorting means arranging all the items in a list in ascending or descending order. We can compare different sorting algorithms by how much time and memory space is required to use them.
    The time taken by an algorithm changes depending on the input size. Moreover, some algorithms are relatively easy to implement, but may perform poorly with respect to time and space complexity, whereas other algorithms are slightly more complex to implement, but can perform well when sorting longer lists of data. One of the sorting algorithm, merge sort, we have already discussed in Chapter 3 , Algorithm Design Techniques and Strategies . We will discuss several more sorting algorithms one by one in detail along with their implementation details, starting with the bubble sort algorithm.

    Bubble sort algorithms

    The idea behind the bubble sort algorithm is very simple. Given an unordered list, we compare adjacent elements in the list, and after each comparison, we place them in the right order according to their values. So, we swap the adjacent items if they are not in the correct order. This process is repeated n-1 times for a list of n
  • 50 Algorithms Every Programmer Should Know
    eBook - ePub

    50 Algorithms Every Programmer Should Know

    An unbeatable arsenal of algorithmic solutions for real-world problems

    The ability to efficiently sort and search items in a complex data structure is important as it is needed by many modern algorithms. The right strategy to sort and search data will depend on the size and type of the data, as discussed in this chapter. While the end result is exactly the same, the right sorting and searching algorithm will be needed for an efficient solution to a real-world problem. Thus, carefully analyzing the performance of these algorithms is important.
    Sorting algorithms are used extensively in distributed data storage systems such as modern NoSQL databases that enable cluster and cloud computing architectures. In such data storage systems, data elements need to be regularly sorted and stored so that they can be retrieved efficiently.
    The following sorting algorithms are presented in this chapter:
    • Bubble sort
    • Merge sort
    • Insertion sort
    • Shell sort
    • Selection sort
    But before we look into these algorithms, let us first discuss the variable-swapping technique in Python that we will be using in the code presented in this chapter.

    Swapping variables in Python

    When implementing sorting and searching algorithms, we need to swap the values of two variables. In Python, there is a standard way to swap two variables, which is as follows:
    var_1 = 1 var_2 = 2 var_1, var_2 = var_2, var_1 print (var_1,var_2)
    2, 1 This simple way of swapping values is used throughout the sorting and searching algorithms in this chapter. Let’s start by looking at the bubble sort algorithm in the next section.

    Bubble sort

    Bubble sort is one of the simplest and slowest algorithms used for sorting. It is designed in such a way that the highest value in a list of data bubbles makes its way to the top as the algorithm loops through iterations. Bubble sort requires little runtime memory to run because all the ordering occurs within the original data structure. No new data structures are needed as temporary buffers. But its worst-case performance is O(N2) , which is quadratic time complexity (where N is the number of elements being sorted). As discussed in the following section, it is recommended to be used only for smaller datasets. Actual recommended limits for the size of the data for the use of bubble sort for sorting will depend on the memory and the processing resources available but keeping the number of elements (N
  • Data Structures and Algorithm Analysis in C++, Third Edition
    Quicksort’s worst case arises when the pivot does a poor job of splitting the array into equal size subarrays. If we are willing to do more work searching for a better pivot, the effects of a bad pivot can be decreased or even eliminated. One good choice is to use the “median of three” algorithm, which uses as a pivot the middle of three randomly selected values. Using a random number generator to choose the positions is relatively expensive, so a common compromise is to look at the first, middle, and last positions of the current subarray. However, our simple findpivot function that takes the middle value as its pivot has the virtue of making it highly unlikely to get a bad input by chance, and it is quite cheap to implement. This is in sharp contrast to selecting the first or last element as the pivot, which would yield bad performance for many permutations that are nearly sorted or nearly reverse sorted. A significant improvement can be gained by recognizing that Quicksort is relatively slow when n is small. This might not seem to be relevant if most of the time we sort large arrays, nor should it matter how long Quicksort takes in the rare instance when a small array is sorted because it will be fast anyway. But you should notice that Quicksort itself sorts many, many small arrays! This happens as a natural by-product of the divide and conquer approach. A simple improvement might then be to replace Quicksort with a faster sort for small numbers, say Insertion Sort or Selection Sort. However, there is an even better — and still simpler — optimization. When Quicksort partitions are below a certain size, do nothing! The values within that partition will be out of order. However, we do know that all values in the array to the left of the partition are smaller than all values in the partition. All values in the array to the right of the partition are greater than all values in the partition
  • Machine Learning for Decision Sciences with Case Studies in Python
    • S. Sumathi, Suresh Rajappa, L Ashok Kumar, Surekha Paneerselvam(Authors)
    • 2022(Publication Date)
    • CRC Press
      (Publisher)
    Figure 2.22 .
    FIGURE 2.22
    Quicksort.
    2.4.5.20 Data Structures in Python with Sample Codes
    The purpose of data structures is to hold some data together. It is used to store a collection of data. There are four built-in data structures in Python − list, tuple, dictionary, and set.
    2.4.5.20.1 List
    A list is a data structure that holds an ordered and similar collection of items, that is, one can store a sequence of members in a given list. In Python, the list is initialized with square brackets, and each item is comma-separated. Items in a list are stored with an index. Once the items are stored in the list, they are changeable in the future. This is easy to imagine if the user wants to store the student’s name of a class; the student’s name can be similar and is ordered.
    1. Example:
    2. StudentName [“Alice”, “Luna”, “Alice”, “Mack”, “Jhon”]
    3. Output: [“Alice”, “Luna”, “Alice”, “Mack”, “Jhon”]
    4. If the user wants to access the 1 st element of a list: print (StudentName[0])
    2.4.5.20.2 Tuple
    The main purpose of the tuple is to hold multiple objects. They are very similar to lists but lack the extensive functionality that list offers, that is, items not changeable once stored. To create a tuple, specific items need to be defined separated by commas within an optional pair of parenthesis. If the user wants to store final marks scored by students in different subjects,
    1. Mack=(“Science”, 20, “English” 30)
    2. Output : (Science”, 20, “English” 30)
    2.4.5.20.3 Dictionary
    Dictionary is like a box of an unordered set of objects. It acts like a telephone dictionary that saves the telephone numbers based on a person’s name, the dictionary’s key, and phone numbers will be its details. In the dictionary, the key should always be unique.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.