Computer Science

Python Sorting

Python Sorting refers to the process of arranging a list of elements in a specific order. Python provides built-in functions such as sorted() and sort() to sort lists in ascending or descending order. Sorting algorithms such as Bubble Sort, Merge Sort, and Quick Sort can also be implemented in Python.

Written by Perlego with AI-assistance

7 Key excerpts on "Python Sorting"

  • 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
  • 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)

    Sorting

    Sorting means reorganizing the data in such as way that it is in the order of smallest to largest. Sorting is one of the most important issues in data structures and computing. Data is regularly sorted before being sorted, as it can then very efficiently be retrieved, be it 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
    • Quick sort
    • Heap sort
    In this chapter, we compare different sorting algorithms by considering their asymptotic behavior. Some of the algorithms are relatively easy to develop, but may perform poorly, whereas other algorithms are slightly more complex to implement, but show good performance in sorting the list when we have a long lists.
    After sorting, it becomes much easier to conduct search operations on a collection of items. We'll start with the simplest of all sorting algorithms; that is, the bubble sort algorithm.
    Passage contains an image

    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-Second-Edition/tree/master/Chapter10 .
    Passage contains an image

    Sorting algorithms

    Sorting means arranging all the items in a list in ascending order of their magnitude. We will be discussing some of the most important sorting algorithms, which each have different performance attributes with respect to runtime complexity. Sorting algorithms are categorized by their memory usage, complexity, recursion, and whether they are comparison-based, among other considerations.
    Some of the algorithms use more CPU cycles, and, as such, have bad asymptotic values. Other algorithms chew on more memory and other computing resources as they sort a number of values. Another consideration is how sorting algorithms lend themselves to being expressed recursively, iteratively, or both. There are algorithms that use comparison as the basis for sorting elements. An example of this is the bubble sort algorithm. Examples of a non-comparison sorting algorithm are the bucket sort and pigeonhole sort algorithms.
  • An Introduction to Python Programming: A Practical Approach
    eBook - ePub

    An Introduction to Python Programming: A Practical Approach

    step-by-step approach to Python programming with machine learning fundamental and theoretical principles.

    • Dr. Krishna Kumar Mohbey; Dr. Brijesh Bakariya(Author)
    • 2021(Publication Date)
    • BPB Publications
      (Publisher)
    Sorting means arranging the data in either ascending or descending order. The primary task of sorting algorithms is to organize data elements in a particular order. If our data is properly sorted in order, then it would search the element fast. Moreover, sorting maintains the data structure. Sorting may also be used to display data in a more readable format. Sorting can be used in a variety of contexts, including the dictionary, telephone directory, and so on.
    Python uses the sort() method for sorting elements of a given list in a specific ascending or descending order. The syntax of the sort() method is:
    Syntax: list.sort(key=…, reverse=…) sorted(list, key=…, reverse=…)
    An important point which we have to remember is the basic difference between sort() and sorted() is that the sort() method changes the list directly and doesn't return any value, while sorted() doesn't change the list and returns the sorted list.
    In the sort() and sorted() methods, there are two parameters: reverse and key . The sorted list is reversed if the reverse parameter is true. A key parameter is used as a sort comparison key.
    Let us take an example to understand this concept. Example 6.43: vowels_var = ['i', 'a', 'u', 'o', 'e'] # vowels list vowels_var.sort() # sort the vowels print ('Sorted list:', vowels_var) # print vowels vowels_var = ['i', 'a', 'u', 'o', 'e'] # vowels list vowels_var.sort(reverse=True) #Sort the list in Descending order print ('Sorted list:', vowels_var) # print vowels #Custom Sorting With key list1 = ['ppp', 'aaaa', 'd', 'bb'] print (sorted(list1, key=len)) #Sort the list by the length of the values: def my_sort_fun(n): return len(n) faculty = ['Brijesh', 'Krishna', 'Amit', 'Zubin'] faculty.sort(key=my_sort_fun) Output: Sorted list: ['a', 'e', 'i', 'o', 'u'] Sorted list: ['u', 'o', 'i', 'e', 'a'] ['d', 'bb', 'ppp', 'aaaa']

    Types of sorting

    The following are the various types of sorting:
    • In-place sorting
  • 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
  • The Self-Taught Computer Scientist
    eBook - ePub

    The Self-Taught Computer Scientist

    The Beginner's Guide to Data Structures & Algorithms

    • Cory Althoff(Author)
    • 2021(Publication Date)
    • Wiley
      (Publisher)
    When you are building your programs in the real world, you should almost always use your programming language's built-in sorting function. You should not implement the classic sorting algorithms discussed here (except in rare circumstances) because modern programming languages like Python have built-in sorting functions that are faster. However, learning a few of the classic sorting algorithms will help you better understand time complexity and teach you concepts you can use in situations other than sorting, such as the merge step in a merge sort.

    Bubble Sort

    Bubble sort is a sorting algorithm where you iterate through a list of numbers, compare each number to the next number, and swap them if they are out of order. Computer scientists call it a bubble sort because the numbers with the highest values “bubble up” to the end of the list, and the numbers with the smallest values move to the beginning of the list as the algorithm progresses.
    Say you have the following list:
    [32, 1, 9, 6]
    First, you compare 1 and 32:
    [32, 1, 9, 6]
    Thirty-two is bigger, so you swap them:
    [1, 32, 9, 6]
    Next, you compare 32 and 9:
    [1, 32, 9, 6]
    Thirty-two is larger, so you swap them again:
    [1, 9, 32, 6]
    Finally, you compare 32 and 6:
    [1, 9, 32, 6]
    Once again, you swap them:
    [1, 9, 6, 32]
    As you can see, 32 “bubbled up” to the end of the list. However, your list is still not in order because 9 and 6 are not in the right spots. So, your algorithm starts at the beginning again and compares 1 and 9:
    [1, 9, 6, 32]
    Nothing happens because 1 is not greater than 9. Next, it compares 9 and 6:
    [1, 9, 6, 32]
    Nine is greater than 6, so you swap them, and your list is now in order:
    [1, 6, 9, 32]
    In a bubble sort, the largest number in your list will move to the end of your list at the end of your algorithm's first iteration, but if the smallest number in your list starts at the end, it will take multiple passes for your algorithm to move it to the beginning of your list. For instance, in this example, 32 ended up at the end of your list after one iteration. Say your list started like this, though:
  • PHP 7 Data Structures and Algorithms

    Using Sorting Algorithms

    Sorting is one of the most used algorithms in computer programming. Even in our everyday life, if things are not sorted, we can have a hard time with them. Sorting can pave the way for faster searching or ordering of items in a collection. Sorting can be done in many different ways, such as in ascending order or descending order. Sorting can also be based on the type of data. For example, sorting a collection of names will require lexicographical sorting rather than numerical sorting. As sorting can play an important role for other data structures and their efficiencies, there are many different sorting algorithms available. We will explore a few of the most popular sorting algorithms in this chapter, along with their complexity and usages.
    Passage contains an image

    Understanding sorting and their types

    Sorting means a sorted order of the data. Often, our data is unsorted, which means we need a way to sort it. Usually, sorting is done by comparing different elements with each other and coming up with the ranking. In most cases, without the comparison, we cannot decide on the sorting part. After the comparison, we also need to swap the elements so that we can reorder them. A good sorting algorithm has the characteristics of making a minimum number of comparisons and swapping. There is also non-comparison based sorting, where no comparison is required to sort a list of items. We will also explore those algorithms in this chapter.
    Sorting can be classified into different types based on the type of data set, direction, computational complexities, memory usage, space usage, and so on. Here are few of the sorting algorithms we will explore in this chapter:
    • Bubble sort
    • Insertion sort
    • Selection sort
    • Quick sort
    • Merge sort
    • Bucket sort
    We will keep our discussion limited to the preceding list, as they are the most commonly used sorting algorithms and can be grouped and classified under different criteria such as simple sorting, efficient sorting, distribution sorting, and so on. We will now explore each of the sorting functionalities, their implementations, and complexity analysis, along with their pros and cons. Let's get started with the most commonly used sorting algorithm - bubble sort.
  • Data Structures and Algorithm Analysis in C++, Third Edition
    PART III

    Sorting and Searching

    Passage contains an image

    7

    Internal Sorting

    We sort many things in our everyday lives: A handful of cards when playing Bridge; bills and other piles of paper; jars of spices; and so on. And we have many intuitive strategies that we can use to do the sorting, depending on how many objects we have to sort and how hard they are to move around. Sorting is also one of the most frequently performed computing tasks. We might sort the records in a database so that we can search the collection efficiently. We might sort the records by zip code so that we can print and mail them more cheaply. We might use sorting as an intrinsic part of an algorithm to solve some other problem, such as when computing the minimum-cost spanning tree (see Section 11.5).
    Because sorting is so important, naturally it has been studied intensively and many algorithms have been devised. Some of these algorithms are straightforward adaptations of schemes we use in everyday life. Others are totally alien to how humans do things, having been invented to sort thousands or even millions of records stored on the computer. After years of study, there are still unsolved problems related to sorting. New algorithms are still being developed and refined for special-purpose applications.
    While introducing this central problem in computer science, this chapter has a secondary purpose of illustrating issues in algorithm design and analysis. For example, this collection of sorting algorithms shows multiple approaches to using divide-and-conquer. In particular, there are multiple ways to do the dividing: Mergesort divides a list in half; Quicksort divides a list into big values and small values; and Radix Sort divides the problem by working on one digit of the key at a time. Sorting algorithms can also illustrate a wide variety of analysis techniques. We’ll find that it is possible for an algorithm to have an average case whose growth rate is significantly smaller than its worse case (Quicksort). We’ll see how it is possible to speed up sorting algorithms (both Shellsort and Quicksort) by taking advantage of the best case behavior of another algorithm (Insertion sort). We’ll see several examples of how we can tune an algorithm for better performance. We’ll see that special case behavior by some algorithms makes them a good solution for special niche applications (Heapsort). Sorting provides an example of a significant technique for analyzing the lower bound for a problem. Sorting will also be used to motivate the introduction to file processing presented in Chapter 8.
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.