Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

radix sort python

def radixSort(inputArray, base = None):
    """Sort elements by powers using buckets to store lists based on integer columns"""    
    if base is None:
      base = 10  ## For decimals
    
    ## Check for the non negative number as this method is only applicable for non negative numbers
    assert len({i <= 0 for i in inputArray}) == 1, 'Non negative numbers in the list'
        
    n = 0
    max_digit = len(str(max(inputArray)))  # find max number and get length of digits 
    

    while max_digit > n:
        bucket = [[] for _ in range(10)]        # create buckets (2D array), 10 is used as we are using decimal and distinct value of last digit is 10
        for i in inputArray:
            bucket[i//(base**n)%10].append(i)   # put corrensponding numbers in bucket
        index = 0
        for i in range(len(bucket)):       # loop through bucket
            
            stage_two = bucket[i]          # find lists of numbers in bucket
            for nums in stage_two:
                inputArray[index] = nums     # add sorted list back into original list
                index += 1
        n += 1     # increasing the power of n

    return inputArray
  
## Terst Case
assert radixSort([170, 45, 75, 90, 2, 802, 2, 66]) == [2, 2, 45, 66, 75, 90, 170, 802], "The radix sort failed"
Comment

radix sort python

def countingSortForRadix(inputArray, placeValue):
    # We can assume that the number of digits used to represent
    # all numbers on the placeValue position is not grater than 10
    countArray = [0] * 10
    inputSize = len(inputArray)

    # placeElement is the value of the current place value
    # of the current element, e.g. if the current element is
    # 123, and the place value is 10, the placeElement is
    # equal to 2
    for i in range(inputSize): 
        placeElement = (inputArray[i] // placeValue) % 10
        countArray[placeElement] += 1

    for i in range(1, 10):
        countArray[i] += countArray[i-1]

    # Reconstructing the output array
    outputArray = [0] * inputSize
    i = inputSize - 1
    while i >= 0:
        currentEl = inputArray[i]
        placeElement = (inputArray[i] // placeValue) % 10
        countArray[placeElement] -= 1
        newPosition = countArray[placeElement]
        outputArray[newPosition] = currentEl
        i -= 1
        
    return outputArray

def radixSort(inputArray):
    # Step 1 -> Find the maximum element in the input array
    maxEl = max(inputArray)

    # Step 2 -> Find the number of digits in the `max` element
    D = 1
    while maxEl > 0:
        maxEl /= 10
        D += 1
    
    # Step 3 -> Initialize the place value to the least significant place
    placeVal = 1

    # Step 4
    outputArray = inputArray
    while D > 0:
        outputArray = countingSortForRadix(outputArray, placeVal)
        placeVal *= 10  
        D -= 1

    return outputArray
    
input = [2,20,61,997,1,619]
print(input)
sorted = radixSort(input)
print(sorted)
Comment

Radix sort in Python

# Radix sort in Python


# Using counting sort to sort the elements in the basis of significant places
def countingSort(array, place):
    size = len(array)
    output = [0] * size
    count = [0] * 10

    # Calculate count of elements
    for i in range(0, size):
        index = array[i] // place
        count[index % 10] += 1

    # Calculate cumulative count
    for i in range(1, 10):
        count[i] += count[i - 1]

    # Place the elements in sorted order
    i = size - 1
    while i >= 0:
        index = array[i] // place
        output[count[index % 10] - 1] = array[i]
        count[index % 10] -= 1
        i -= 1

    for i in range(0, size):
        array[i] = output[i]


# Main function to implement radix sort
def radixSort(array):
    # Get maximum element
    max_element = max(array)

    # Apply counting sort to sort elements based on place value.
    place = 1
    while max_element // place > 0:
        countingSort(array, place)
        place *= 10


data = [121, 432, 564, 23, 1, 45, 788]
radixSort(data)
print(data)
Comment

PREVIOUS NEXT
Code Example
Python :: list sort by key python 
Python :: changing the current working directory in python 
Python :: Converting List to Dataframe Using zip() function 
Python :: selection sort python 
Python :: python file size in bytes 
Python :: integer colomn to datetime 
Python :: returns the smallest positive integer python 
Python :: cant install tensorflow pip python 3.6 
Python :: Return a Series containing counts of unique values. 
Python :: install python 3.6 on centos 
Python :: example of django template for forms 
Python :: python merge two dictionaries in a single expression 
Python :: how to use the random module in python 
Python :: xa python 
Python :: extend tuple python 
Python :: python print color 
Python :: python get desktop directory 
Python :: twin axis python 
Python :: keras callbacks learning rate scheduler 
Python :: excel get unique values from column formula 
Python :: beautifulsoup remove all html tags 
Python :: matplotlib custom legend 
Python :: np argmin top n 
Python :: tf-idf python implementation 
Python :: convert a column to int pandas 
Python :: how to append a number to a list in python 
Python :: create an array of n same value python 
Python :: hardest python questions 
Python :: argparse required arguments 
Python :: NumPy unique Syntax 
ADD CONTENT
Topic
Content
Source link
Name
2+6 =