C++ 排序

sort使用
// alg_sort.cpp
// compile with: /EHsc
#include <vector>
#include <algorithm>  //sort必须
#include <functional>      // For greater<int>( )
#include <iostream>

// Return whether first element is greater than the second
bool UDgreater ( int elem1, int elem2 )
{
	return elem1 > elem2;//降序
}

int main( )
{
	using namespace std;
	vector <int> v1;
	vector <int>::iterator Iter1;

	int i;
	for ( i = 0 ; i <= 5 ; i++ )
	{
		v1.push_back( 2 * i );
	}

	int ii;
	for ( ii = 0 ; ii <= 5 ; ii++ )
	{
		v1.push_back( 2 * ii + 1 );
	}

	cout << "Original vector v1 = ( " ;
	for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
		cout << *Iter1 << " ";
	cout << ")" << endl;

	sort( v1.begin( ), v1.end( ) );
	cout << "Sorted vector v1 = ( " ;
	for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
		cout << *Iter1 << " ";
	cout << ")" << endl;

	// To sort in descending order. specify binary predicate
	sort( v1.begin( ), v1.end( ), greater<int>( ) );
	cout << "Resorted (greater) vector v1 = ( " ;
	for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
		cout << *Iter1 << " ";
	cout << ")" << endl;

	// A user-defined (UD) binary predicate can also be used
	sort( v1.begin( ), v1.end( ), UDgreater );
	cout << "Resorted (UDgreater) vector v1 = ( " ;
	for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
		cout << *Iter1 << " ";
	cout << ")" << endl;
}
  


内部排序:插入 选择 交换

1.插入排序
用直接插入排序法
//从小到大
//直接插入排序函数模板
template<class T>
void insertionSort(T arr[],int n)
{
	for(int i=0;i<n;i++)
	{
//从a[i - 1]开始向a[0]方向扫描各元素,寻找适当位置插入arr[i]
		T tem=arr[i];
		int j=i;
		while (j>0 && tem<arr[j-1])//tem进行比较
		{
			arr[j]=arr[j-1];
			j--;
		}
		arr[j]=tem;
	}
}

2.选择排序
直接选择排序
每次从待排序序列中选择一个关键字最小的元素,(当需要按关键字升序排列时),顺序排在已排序序列的最后,直至全部排完。
//从小到大
void mySwap(T &a,T &b)
{
	T tem;
	tem=a;
	a=b;
	b=tem;
}

template<class T>
void selectionSort(T arr[],int n)
{
	for (int i=0;i<n-1;i++)
	{
		int leastIndex = i;	//最小元素之下标初值设为i
		for (int j=i+1;j<n;j++)
		{
			if (arr[j]<arr[leastIndex])
			{
				leastIndex=j;
			}
		}
		mySwap(arr[i],arr[leastIndex]);
	}
}

3.交换排序 冒泡排序
发生交换的位置必定小于n,且这个位置之后的数据必定已经有序了,记录下这位置
template<class T>
void mySwap(T &a,T &b)
{
	T tem;
	tem=a;
	a=b;
	b=tem;
}

template<class T>
void bubbleSort(T arr[],int n)
{
//发生交换的位置必定小于n,且这个位置之后的数据必定已经有序了,记录下这位置
	int i=n-1;
	while (i>0)
	{
		int lastExchangeIndex = 0;	//必须每次都初始化为0
		for (int j=0;j<i;j++)
		{
			if (arr[j+1]<arr[j])
			{
				mySwap(arr[j+1],arr[j]);
				lastExchangeIndex=j;
			}
		}
		i=lastExchangeIndex;
	}
}


查找: 顺序查找 折半查找

4.顺序查找
//顺序查找函数模板
template <class T>
int SeqSearch(T list[],int n,T key)
{
		for(int i=0;i < n;i++)
		if (list[i] == key)
			return i;
		return -1;
}

5.折半查找

template<class T>
int  binSearch(const T list[], int n, const T &key)
{
	int low=0,high=n-1;
	while (low<=high)//必须是<=号
	{
		int mid=(low+high)/2;
		if (key==list[mid])//是和list[mid] 进行的操作
		    return mid;
		else if (key<list[mid])
			high=mid-1;
		else
			low=mid+1;
	}
	return -1;
}



你可能感兴趣的:(C++ 排序)