#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include <math.h>
using namespace std;
typedef float Type;
float Numbers[1000];
int num = 0;
void readNumber(ifstream& fin1);
void QuickSort(Type a[], int p, int r);
int Partition(Type a[], int p, int r);
int RandomizedPartition(Type a[], int p, int r);
void Swap(Type a[], int i, int j);
int Random(int p, int r);
int main(int argc, char *argv[])
{
ifstream fin1("numbers.txt"); //存放待排序数据的文件,一行一个数据
readNumber(fin1); //按行读取数据
fin1.close();
QuickSort(Numbers,0,num-1);
for(int i=0;i<num;i++)
{
printf("%4d %8.1f\n",i+1,Numbers[i]);
}
char dummy_char;
cin>>dummy_char;
return 0;
}
void readNumber(ifstream& fin1) //把文件里的数值读入数值Numbers
{
if (!fin1)
{
cerr<<"could not open data file";
exit(1);
}
string line;
while(!fin1.eof())
{
getline(fin1, line);
std::stringstream stream(line);
stream>>Numbers[num];
num++;
}
}
void QuickSort(Type a[], int p, int r)
{
if (p < r)
{
int q = RandomizedPartition(a, p, r);
QuickSort(a, p, q-1);
QuickSort(a, q+1, r);
}
}
int Partition(Type a[], int p, int r)
{ _
int i = p, j = r + 1;
Type x = a[p];
while (true) {
while (a[++i] <x && i<r);
while (a[--j] >x);
if (i >= j) break;
Swap(a, i, j);
}
a[p] = a[j];
a[j] = x;
return j;
}
int RandomizedPartition(Type a[], int p, int r) //随机快速排序
{
int i = Random(p, r);
Swap(a,i,p);
return Partition(a, p, r);
}
void Swap(Type a[], int i, int j)
{
Type temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
int Random(int p, int r)
{
return rand()%(r-p)+p;
}