⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sort_s.cpp

📁 一个小型的排序算法
💻 CPP
字号:
// sort_s.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

template <class ty>
class array
{
public:
	array(int size_s = default_size)
	{
		theBuf_ = new ty[size_s];
		length_ = size_s;
	}
	array(ty *buf, int length)
	{
		//ASSERT(buf);
		theBuf_ = new ty[length];
		length_ = length;
		for (int i = 0; i < length_; i++)
		{
			theBuf_[i] = buf[i];
		}
	}
	array(const array& ma)
	{
		*this = ma;
	}

	array& operator = (const array& ma)
	{
		delete []theBuf_;
		theBuf_ = new ty[ma.GetLength()]
		for (int i = 0; i < ma.GetLength(); i++)
		{
			theBuf_[i] = ma[i];
		}
		return *this;
	}

	void loadBuf(ty *buf, int length)
	{
		if (theBuf_)
		{
			delete theBuf_;
		}
		length_ = length;
		for (int i = 0; i < length_; i++)
		{
			theBuf_[i] = buf[i];
		}
	}


	ty& operator [](int i)
	{
		return theBuf_[i];
	}

	int GetLength()
	{
		return length_;
	}

	void Print()
	{
		cout<<endl;
		for (int i = 0; i < length_; i++)
		{
			cout <<theBuf_[i]<<" ";
		}
		cout << endl;
	}

private:
	ty *theBuf_;
	int length_;
	const static int default_size = 10;
};

template <class ty>
ty _min(ty x, ty y)
{
	if (x > y)
	{
		return x;
	}
	else
		return y;
}

template <class ty>
void swap(array<ty> &ar, int x, int y)
{
	if (x >= 0 && x < ar.GetLength() && y >= 0 && y < ar.GetLength())
	{
		ty temp = ar[y];
		ar[y] = ar[x];
		ar[x] = temp;
	}
	else
	{
		cerr<<"error!"<<endl;
	}
}

template <class ty>
void Sort_s(array<ty>& ay, int low, int high)
{
	if (low < high)
	{
		int lo = low;
		int hi = high + 1;
		ty elem = ay[lo];

		for (;;)
		{
			while (_min(ay[++lo], elem) != elem && lo < high);
			while (_min(ay[--hi], elem) == elem && hi > low);
			if (lo < hi)
			{
				swap(ay, lo, hi);
			}
			else
			{
				break;
			}
		}

		swap(ay, low, hi);
		Sort_s(ay, low, hi - 1);
		Sort_s(ay, hi + 1, high);
	}
}


int _tmain(int argc, _TCHAR* argv[])
{
	int x[5] = {10, 28, 25, 54, 4};
	array<int> array1(x, 5); 
	array1.Print();
	Sort_s(array1, 0, array1.GetLength() - 1);
	array1.Print();
	char dump;
	cin>>dump;
	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -