快速排序程序(windows vs)

来源:互联网 发布:微软office for mac 编辑:程序博客网 时间:2024/06/08 13:48
// 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;//中轴值的indexwhile(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;}

0 0
原创粉丝点击