I wrote the count sort code but it is showing me weird output, can you tell where I am wrong ??
#include <bits/stdc .h>
using namespace std;
void CountSort(int a[], int n, int k)
{
int count[k 1]={0};
int b[n];
for (int i = 0; i < n; i )
{
count[a[i]];
}
for (int i = 1; i <= k; i )
{
count[i] = count[i - 1];
}
for (int i = 0; i >= 0; i--)
{
b[count[a[i]]-1] = a[i];
--count[a[i]];
}
for (int i = 0; i < n; i )
{
a[i] = b[i];
}
}
int main()
{
int a[] = {2, 1, 1, 0, 2, 5, 4, 0, 2, 8, 7, 7, 9, 2, 0, 1, 9};
CountSort(a, 17, 9);
cout<<"The sorted array is -> "<<a;
return 0;
}
It gives output like this -
The sorted array is -> 0x7bfdd0
ScreenShot of the code and the output
CodePudding user response:
When trying to print the array, you cannot just use std::cout << a. At the moment your code is printing the memory address of the array a, which is not what you want.
To fix the problem, print all elements of the array, one by one. These loops can be helpful:
for (const auto& elem : a)
std::cout << elem << " ";
Or
for (int i = 0; i < sizeof(a) / sizeof(int); i )
std::cout << a[i] << " ";
CodePudding user response:
Your code have two fault.
- print array method is wrong.
- third loop is wrong in
CountSort. this loop working only once.
There is fix result.
void CountSort(int a[], int n, int k)
{
int count[k 1]={0};
int b[n];
for (int i = 0; i < n; i )
{
count[a[i]];
}
for (int i = 1; i <= k; i )
{
count[i] = count[i - 1];
}
for (int i = 0; i < n; i )
{
b[count[a[i]]-1] = a[i];
--count[a[i]];
}
for (int i = 0; i < n; i )
{
a[i] = b[i];
}
}
int main()
{
int a[] = {2, 1, 1, 0, 2, 5, 4, 0, 2, 8, 7, 7, 9, 2, 0, 1, 9};
CountSort(a, 17, 9);
cout<<"The sorted array is -> ";
for (int i = 0; i < 17; i) {
cout << a[i] << ' ';
}
cout << endl;
return 0;
}
result:
The sorted array is -> 0 0 0 1 1 1 2 2 2 2 4 5 7 7 8 9 9
