Assignment_Week2
Assignment_Week2
ID : 410921363
Algorithm Lab
Week 2: Non-Comparison Sort
Description
Classical sorting algorithms are algorithms rearrange the input list to a certain order defined
by the comparison function. For some special domain (in most case, subdomain of natural
numbers), we can design special sorting algorithms that working without generalized
comparison functions, respectively, non-comparison sorting algorithms.
Algorithm Design
Language: C
void sort_by_digit(int *A, int n, int r, int p)
{
int base = 1;
while (p > 0)
{
--p;
base *= r;
}
int count[r], B[n], m = 0;
for (int j = 0; j < r; ++j)
count[j] = 0;
for (int i = 0; i < n; ++i)
count[(A[i] / base) % r]++;
for (int j = 0, psum = 0, sum = 0; j < r; ++j)
{
psum = sum;
sum += count[j];
count[j] = psum;
}
for (int i = 0; i < n; ++i)
B[count[(A[i] / base) % r]++] = A[i];
for (int i = 0; i < n; ++i)
A[i] = B[i];
}
void radix_sort(int *A, int n, int r, int d)
{
for (int i = 0; i < d; ++i)
sort_by_digit(A, n, r, i);
}
Questions
Answer
1. False, in order for radix sort to work correctly, the digit sorts must be stable.
Integers that are equal in some digits aren't always equal (e.g., 12 and 13). Let's
sort [13, 12] using an LSD-first radix sort (base 10). But we'll use an unstable sort for
each digit.
First, we sort by the 1's place, so the array becomes [12, 13]. Now we sort by the 10's
places, but 12 and 13 have the same digit.
Since the sort is unstable, the resulting array could be [12, 13] or [13, 12]. We don't
know. If the sort were stable, we would be guaranteed to get a correctly sorted array.
2. Usually, it's by digit instead of bit. But the reason remains the same regardless: if you
sort by least significant digit first, then by the time you've sorted by most significant
digit, the numbers are all sorted in the way we would normally sort them (for a set of
non-negative numbers).
If you sort the other direction, you would put 92 before 18, because you sort the least
significant bits last.
It's similar to how you would sort names: if you want Last, First to be sorted, you
could sort First, then do a stable sort that sorts Last. If you do it the other way around,
the names won't be in the order you want.
3.
#include <iostream>
return d;
}
return max + 1;
}
int main() {
long long int arr[8] = {213, 456, 784, 3552, 23031, 322556, 2252236, 56488
56};
return 0;
}
4. Time Complexity
Radix Sort takes O(d*(n+b)) time where b is the base for representing numbers,
for example, for the decimal system, b is 10. What is the value of d? If k is the maximum
possible value, then d would be O(logb(k)). So overall time complexity is O((n+b)*
logb(k)).