In Counting sort, the frequencies of distinct elements of the array to be sorted is counted and stored in an auxiliary array, by mapping its value as an index of the auxiliary array.
Algorithm:
Let's assume that, array of size needs to be sorted.
- Initialize the auxillary array as .
Note: The size of this array should be . - Traverse array and store the count of occurrence of each element in the appropriate index of the array, which means, execute
Aux[A[i]]++
for each , where ranges from . - Initialize the empty array
- Traverse array and copy into for number of times where .
Note: The array can be sorted by using this algorithm only if the maximum value in array is less than the maximum size of the array . Usually, it is possible to allocate memory up to the order of a million . If the maximum value of exceeds the maximum memory- allocation size, it is recommended that you do not use this algorithm. Use either the quick sort or merge sort algorithm.
Implementation:
Assume that the maximum element that can be in the array is .
Now take an array of size .
= Array to be sorted.
= Sorted version of .
Now take an array of size .
= Array to be sorted.
= Sorted version of .
void counting_sort(int A[], int Aux[], int sortedA[], int N) {
// First, find the maximum value in A[]
int K = 0;
for(int i=0; i<N; i++) {
K = max(K, A[i]);
}
// Initialize the elements of Aux[] with 0
for(int i=0 ; i<=K; i++) {
Aux[i] = 0;
}
// Store the frequencies of each distinct element of A[],
// by mapping its value as the index of Aux[] array
for(int i=0; i<N; i++) {
Aux[A[i]]++;
}
int j = 0;
for(int i=0; i<=K; i++) {
int tmp = Aux[i];
// Aux stores which element occurs how many times,
// Add i in sortedA[] according to the number of times i occured in A[]
while(tmp--) {
//cout << Aux[i] << endl;
sortedA[j] = i;
j++;
}
}
}
Example:
Say .
Say .
will be of the size i.e.
.
Notice that which represents the number of occurrences of in . Similarly which represents the number occurrences of in .
Notice that which represents the number of occurrences of in . Similarly which represents the number occurrences of in .
After applying the counting sort algorithm, will be
Time Complexity:
The array is traversed in time and the resulting sorted array is also computed in time. is traversed in time. Therefore, the overall time complexity of counting sort algorithm is .
The array is traversed in time and the resulting sorted array is also computed in time. is traversed in time. Therefore, the overall time complexity of counting sort algorithm is .
Không có nhận xét nào:
Đăng nhận xét