C++常用排序算法的實現

最常用的算法莫過於冒泡排序、選擇排序、插入排序、快速排序、歸併排序和希爾排序這幾種了。

頭文件如下:

#ifndef SORTING_H_
#define SORTING_H_

const static int SG_COUNT = 10;

void BubbleSort(int* pData, int Count);

void SelectSort(int* pData, int Count);

void InsertSort(int* pData, int Count);

void QuickSort(int * pData,int left,int right);

void ShellSort(int * pData, int Count);

void MergeSort(int * pData, int start, int end);
#endif
實現文件如下:

#include "Sorting.h"
#include 
using namespace std;

void swap(int &a,int &b)  //交換
{
	int x;
	x=a;
	a=b;
	b=x;
}

// 冒泡排序BubbleSort()
void BubleSort(int * num, int Count)
{
	for(int a = 0; a < Count-2; a++)  
		for(int b=0; b < Count-a-1; b++)
		{
			if(num[b] > num[b+1])
				swap(num[b], num[b+1]);
		}
}

// 選擇排序SelectSort()
void SelectSort(int * num,int Count)
{
	int min;
	int temp;
	for(int a = 0; a < Count-1 ;a++)
	{
		min = a;
		for(int b = a+1; b=0) && (iTemp < pData[iPos]))
		{
			pData[iPos+1] = pData[iPos];
			iPos--;
		}
		pData[iPos+1] = iTemp;
	}
} 

// 快速排序QuickSort()
void QuickSort(int * pData,int left,int right)
{
	if(left= 1;d = d/2)
	{
		for(i=d; i < Count; i++)
		{
			temp = pData[i];
			for(j = i-d;(j >= 0)&&(pData[j] > temp); j = j-d)
				pData[j+d] = pData[j];
			pData[j+d] = temp;
		}
	}
}

// 合併
void Merge(int array[], int start, int mid, int end)
{
	int temp1[10], temp2[10];
	int n1, n2;
	n1 = mid - start + 1;
	n2 = end - mid;

	for (int i = 0; i < n1; i++)
		temp1[i] = array[start + i];
	for (int i = 0; i < n2; i++)
		temp2[i] = array[mid + i + 1];

	// 把後面的元素設置的很大
	temp1[n1] = temp2[n2] = 1000;

	for (int k = start, i = 0, j = 0; k <= end; k++)
	{
		if (temp1[i] <= temp2[j])
			array[k] = temp1[i++];
		else
			array[k] = temp2[j++];
	}
}


// 歸併排序,MergeSort()
void MergeSort(int * pData, int start, int end)
{
	if (start < end)
	{
		int i;
		i = (end + start) / 2;
		MergeSort(pData, start, i);
		MergeSort(pData, i + 1, end);
		Merge(pData, start, i, end);
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章