快速排序程序(windows vs)

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

#pragma once
#include "stdafx.h"
#include <fstream>
#include <vector>
#include <iostream>
#include <sstream>

using namespace std;

int fileLength = 100000;
int numbers[100000];//存储所有数据的数组

void readData(char* filePath){
	ifstream fin;
	string line;
	int oneNumber;
	stringstream ss;

	fin.open(filePath);

	cout<<"开始读文件..."<<endl;
	int i=0;
	while(getline(fin,line)){
		ss<<line;
		ss>>oneNumber;
		ss.clear();
		numbers[i++] = oneNumber;
		//cout<<"i="<<i<<endl;
	}
	cout<<"读文件结束,i="<<i<<endl;

} 

void printArray(){
	for(int i=0;i<fileLength;i++){
		cout<<numbers[i]<<",";
	}
	cout<<endl;
}

void quickSort(int arrayBegin,int arrayEnd){

	if(arrayBegin>=arrayEnd){
		return;
	}

	//cout<<arrayBegin<<","<<arrayEnd<<endl;

	int leftIndex = arrayBegin;
	int rightIndex = arrayEnd;

	int center = numbers[leftIndex];//选定最左端的元素作为中轴值
	int centerIndex = leftIndex;//中轴值的index

	while(leftIndex<=rightIndex){

		//从后向前找,找到比中轴值小的元素,写到中轴位置处
		while(leftIndex<=rightIndex&&numbers[rightIndex]>=center){
			rightIndex--;
		}
		
		if(leftIndex<=rightIndex){//找到了
			numbers[centerIndex]=numbers[rightIndex];
			centerIndex = rightIndex;
			rightIndex--;
		}
		//从前向后找,找到比中轴值大的元素,写到中轴值位置处
		while(leftIndex<=rightIndex&&numbers[leftIndex]<=center){
			leftIndex++;
		}

		if(leftIndex<=rightIndex){//找到了
			numbers[centerIndex] = numbers[leftIndex];
			centerIndex=leftIndex;
			leftIndex++;
		}
	}
	numbers[centerIndex]=center;
	
	quickSort(arrayBegin,centerIndex-1);
	quickSort(centerIndex+1,arrayEnd);

}

void writeData(char * filePath){
	ofstream fout;
	stringstream ss;
	string s;

	fout.open(filePath);

	cout<<"开始写文件..."<<endl;
	for(int i=0;i<fileLength;i++){
		ss<<numbers[i];
		ss>>s;
		ss.clear();
		fout<<s<<endl;
	}
	cout<<"写文件结束"<<endl;
}



int _tmain(int argc, _TCHAR* argv[])
{
	readData("Q5.txt");
	cout<<"开始快排..."<<endl;
	quickSort(0,fileLength-1);
	cout<<"结束快排..."<<endl;
	writeData("result.txt");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值