關於排序法的c++實例(一)

這裏面的排序發都是相對簡單的,好理解的,我把他們整理了下打包在一個程序裏。還有堆排序啊,或者快速排序什麼的還沒弄懂呢,以後再發啦~

#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;
}


發佈了47 篇原創文章 · 獲贊 29 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章