Нужно использовать рекурсию вместо цикла:
Код: Выделить всё
#include <iostream>
using namespace std;
int a[100], b[100], n;
int digit(int n, int p)
{
return (n >> p & 1);
}
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
int k = sizeof(int);
for(int i = 0; i < k; i++)
{
int c[2] = {0};
for(int j = 0; j < n; j++)
c[digit(a[j],i)]++;
for(int j = 1; j < 2; j++)
c[j] += c[j - 1];
for(int j = n - 1; j > -1;j--)
b[--c[digit(a[j],i)]] = a[j];
for(int j = 0; j < n; j++)
a[j] = b[j];
}
for(int i = 0; i < n; i++)
cout << a[i] <<endl;
return 0;
}
Код: Выделить всё
#include <iostream>
void Input(int n, int t, int* &arr){
std::cout << "Enter " << n+1 << " element: " << std::endl;
std::cin >> arr[n];
if (n < t - 1) Input(++n, t, arr);
}
void Output(int n, int t, int* arr){
std::cout << "arr[" << n + 1 << "]=" << arr[n] << std::endl;
if (n < t - 1) Output(++n, t, arr);
}
void Counter(int countofbits, int n, int t, int* arr, int &count0){
if (arr[n] >> countofbits & 1 == 0)
count0++;
if (n < t - 1) Counter(countofbits, ++n, t, arr, count0);
}
void Sort(int i, int t, int* arr, int* &mirrow, int countofbits, int &count0, int &count1){
mirrow[--((arr[i] >> countofbits & 1 == 0) ? (count0) : (count1))] = arr[i];
if (i > 0) Sort(--i, t, arr, mirrow, countofbits, count0, count1);
}
void Rewriting(int i, int t, int* &arr, int* mirrow){
arr[i] = mirrow[i];
if (i < t - 1) Rewriting(++i, t, arr, mirrow);
}
void Foundation(int countofbits, int t, int* &arr){
int count0, count1;
count0 = 0;
count1 = t;
Counter(countofbits, 0, t, arr, count0);
int* mirrow = (int*)malloc(t*sizeof(int));
Sort(t-1, t, arr, mirrow, countofbits, count0, count1);
Rewriting(0, t, arr, mirrow);
if (countofbits < 8*sizeof(int)) Foundation(++countofbits, t, arr);
}
int main() {
int t;
std::cout << "Enter n: " << std::endl;
std::cin >> t;
int* arr = (int*)malloc(t*sizeof(int));
Input(0, t, arr);
Foundation(0, t, arr);
Output(0, t, arr);
system("pause");
return 0;
}