内排序之快排算法的实现C++

    

某个二维数组存放了一系列的字符串,试利用排序的一些算法(如插入、冒泡、快速排序等)对这些字符串按照字典顺序进行排序。

例如:二维数组的字符串如下:

char  s[][20]={“while”,”if”,“else”,”do”,“for”,”switch”,“case”};


实现代码如下:

头文件模块

targetver.h

#pragma once

// 包括 SDKDDKVer.h 将定义可用的最高版本的 Windows 平台。

// 如果要为以前的 Windows 平台生成应用程序,请包括 WinSDKVer.h,并将
// WIN32_WINNT 宏设置为要支持的平台,然后再包括 SDKDDKVer.h。

#include <SDKDDKVer.h>


stdafx.h

// stdafx.h : 标准系统包含文件的包含文件,
// 或是经常使用但不常更改的
// 特定于项目的包含文件
//

#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>



// TODO:  在此处引用程序需要的其他头文件
#include<iostream>
#include<fstream>
#include<string>
using namespace std;

static const int MAX_N = 100;

class CSortFunc
{
public:
	
	CSortFunc(string );//构造
	void CGetInfo();//读文件信息
	void CQuickSort(int, int);//快排
	bool CFileOut();//输出
	int size(); //数组最大下标
	
private:
	ifstream readfile;
	ofstream writefile;
	string filename;
	string str[MAX_N];
	int count;
};


C++文件模块

stdafx.cpp

// stdafx.cpp : 只包括标准包含文件的源文件
// Sortfunction.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息

#include "stdafx.h"

// TODO:  在 STDAFX.H 中
// 引用任何所需的附加头文件,而不是在此文件中引用

//构造
CSortFunc::CSortFunc(string Fname)
{
	this->filename = Fname;
}

//读取信息
void CSortFunc::CGetInfo()
{
	string thistr;
	int i = 0;
	readfile.open(filename, ios::in);
	//正常关联
	if (readfile.is_open())
	{
		//数据正常
		while (!readfile.eof() && (readfile >> thistr).good())
		{
			str[i] = thistr;
			i++;
		}
		count = i;//数据数量
	}

	readfile.close();
}

//获取最大下标
int CSortFunc::size()
{
	return count - 1;
}

//快排
void CSortFunc::CQuickSort(int left, int right)
{
	int i, j;
	string strt, strtmp;

	//递归出口
	if (left > right)
	{
		return;
	}

	//基准数strtmp
	strtmp = str[left];
	i = left;
	j = right;

	while (i != j)
	{
		//哨兵先从右往左
		while (str[j].compare(strtmp) >= 0 && i < j)
		{
			j--;
		}

		//从左往右
		while (str[i].compare(strtmp) <= 0 && i < j)
		{
			i++;
		}

		//交换位置
		if (i < j)
		{
			strt = str[i];
			str[i] = str[j];
			str[j] = strt;
		}
	}

	//正确位置
	str[left] = str[i];
	str[i] = strtmp;

	CQuickSort(left, i - 1);//递归左侧
	CQuickSort(i + 1, right);//右侧
}

//保存结果
bool CSortFunc::CFileOut()
{
	writefile.open("sortfile.txt", ios::out);

	for (int i = 0; i < count; i++)
	{
		writefile << str[i] << endl;
	}

	writefile.close();
	return true;
}


Sortfunction.cpp

// Sortfunction.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"


int _tmain(int argc, _TCHAR* argv[])
{
	CSortFunc m_sort("data.txt");
	m_sort.CGetInfo();
	m_sort.CQuickSort(0,m_sort.size());
	if (m_sort.CFileOut())
	{
		cout << "OK." << endl;
	}
	return 0;
}


数据模块

源数据文件

data.txt

while
if
else
do
for
switch
case


结果数据文件

sortfile.txt

case
do
else
for
if
switch
while



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值