冒泡排序,插入排序,基数排序(三种)
#include <iostream>
using namespace std;
void print(int* pData, int count){
for (int i = 0; i< count; i++) {
cout << pData[i] << " ";
}
cout << endl;
}
void BubbleSort(int* pData, int count)
{
int temp;
for (int i = 1; i < count; i++)
{
for (int j = count - 1; j >= i; j--)
{
if (pData[j] < pData[j - 1])
{
temp = pData[j - 1];
pData[j - 1] = pData[j];
pData[j] = temp;
}
}
}
}
void InsertionSort(int *a, int len)
{
for (int j=1; j<len; j++)
{
int key = a[j];
int i = j-1;
while (i>=0 && a[i]>key)
{
a[i+1] = a[i];
i--;
}
a[i+1] = key;
}
}
void printArray(int array[],int length)
{
for (int i = 0; i < length; ++i)
{
cout << array[i] << " ";
}
cout << endl;
}
int maxbit(int data[], int n)
{
int d = 1;
int p = 10;
for(int i = 0; i < n; ++i)
{
while(data[i] >= p)
{
p *= 10;
++d;
}
}
return d;
}
void radixsort(int data[], int n)
{
int d = maxbit(data, n);
int tmp[n];
int count[10];
int i, j, k;
int radix = 1;
for(i = 1; i <= d; i++)
{
for(j = 0; j < 10; j++)
count[j] = 0;
for(j = 0; j < n; j++)
{
k = (data[j] / radix) % 10;
count[k]++;
}
for(j = 1; j < 10; j++)
count[j] = count[j - 1] + count[j];
for(j = n - 1; j >= 0; j--)
{
k = (data[j] / radix) % 10;
tmp[count[k] - 1] = data[j];
count[k]--;
}
for(j = 0; j < n; j++)
data[j] = tmp[j];
radix = radix * 10;
}
}
int main()
{
int a[20] = { };
int k;
cout<<"Input"<<endl;
for(int i = 0;i<20 ;i++)
{
cin>>a[i];
if(a[i] == 0)
{
break;
}
else if(a[i] != 0)
{
k++;
}
}
cout<<"1-Bubble Sort,2-InsertSort,3-Radix Sort"<<endl;
int b;
cin>>b;
if(b == 1)
{
cout<<"Output"<<endl;
cout<<"Bubble Sort"<<endl;
BubbleSort(a, k);
}
else if( b == 2)
{
cout<<"Output"<<endl;
cout<<"Insert Sort"<<endl;
InsertionSort(a, k);
}
else if( b == 3)
{
cout<<"Output"<<endl;
cout<<"Radix Sort"<<endl;
for(int i = 0; i<k ;i++)
{
if(a[i] > 10)
{
cout<<"0"<<endl;
cout<<"End"<<endl;
return 0;
}
}
radixsort(a,k);
}
for(int j = 0 ;j<k ;j++)
{
if(j<k-1)
{
cout<<a[j]<<",";
}
else cout<<a[j];
}
cout<<endl;
cout<<"End"<<endl;
return 0;
}