这里面的排序发都是相对简单的,好理解的,我把他们整理了下打包在一个程序里。还有堆排序啊,或者快速排序什么的还没弄懂呢,以后再发啦~
#include<iostream>
using namespace std;
const int size=20;
void InsertionSort(int*,int);
void ShellSort(int*,int);
void SelectionSort(int*,int);
void HeapSort(int*,int);
void BubbleSort(int*,int);
int main()
{
int data[size],n,i=0;
cout<<"The program will put numbers in order(small to big)\n";
cout<<"Enter the array size (at most 20).\n";
while(!(cin>>n)||(n>=size)||(n<1))
{
cin.clear();
cin.get();
cout<<"data wrong!\n";
cout<<"Another input!\n ";
}
cout<<"Enter the "<<n<<" numbers\n";
cin>>data[0];
while(cin&&i<n-1)
{
i++;
cin>>data[i];
}
InsertionSort(data,n);
ShellSort(data,n);
SelectionSort(data,n);
// HeapSort(data,n);
BubbleSort(data,n);
// QuickSort(data,n);
}
void InsertionSort(int data[],int size)
{
int i,j;
int temp;
for (i = 0; i<=size;i++)
{
temp = data[i];
j=i-1;
while((j>=0) && (data[j] > temp))
{
data[j+1] = data[j];
j--;
}
data[j+1] = temp;
}
cout<<"InsertionSort:\n";
for(int k=0;k<size;k++)
cout<<data[k]<<' ';
cout<<endl;
}
void ShellSort(int data[],int size)
{
for (int gap = size / 2; gap > 0; gap /= 2)
for (int i = gap; i < size; ++i)
{
int key = data[i];
int j = 0;
for( j = i -gap; j >= 0 && data[j] > key; j -=gap)
{
data[j+gap] = data[j];
}
data[j+gap] = key;
}
cout<<"ShellSort:\n";
for(int k=0;k<size;k++)
cout<<data[k]<<' ';
cout<<endl;
}
void SelectionSort(int data[], int size)
{
int i, j, temp, pmin;
for(i = 0; i < size - 1; i ++)
{
pmin = i;
for(j = i + 1; j < size; j ++)
if(data[pmin] > data[j])
pmin = j;
if(pmin != i)
{
temp = data[pmin];
data[pmin] = data[i];
data[i] = temp;
}
}
cout<<"SelectionSort:\n";
for(int k=0;k<size;k++)
cout<<data[k]<<' ';
cout<<endl;
}
void HeapSort(int data[],int size)
{
}
void BubbleSort(int data[],int size)
{
int temp;
int i,j;
for (i = 0; i < size; i++) {
for (j =0; j <size-i-1; j++) {
if (data[j] > data[j+1]) {
temp = data[j+1];
data[j+1] = data[j];
data[j] = temp;
}
}
}
cout<<"BubbleSort:\n";
for(int k=0;k<size;k++)
cout<<data[k]<<' ';
cout<<endl;
}