Radix sort implementation in python
- User
Radix sort implementation in python
Assistant
Radix sort is a non-comparative integer sorting algorithm that sorts the digits of each number in the input array, starting from the least significant digit (LSD) to the most significant digit (MSD). Here's an implementation of LSD Radix sort in Python:
def counting_sort(arr, exp): n = len(arr) output = [0] * n count = [0] * 10 for i in range(n): index = (arr[i] // exp) % 10 count[index] += 1 for i in range(1, 10): count[i] += count[i - 1] i = n - 1 while i >= 0: index = (arr[i] // exp) % 10 output[count[index] - 1] = arr[i] count[index] -= 1 i -= 1 for i in range(n): arr[i] = output[i] def radix_sort(arr): max_val = max(arr) exp = 1 while max_val // exp > 0: counting_sort(arr, exp) exp *= 10 # Example usage arr = [170, 45, 75, 90, 802, 24, 2, 66] radix_sort(arr) print("Sorted array is:") for i in range(len(arr)): print(arr[i], end=" ")
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.