zoukankan      html  css  js  c++  java
  • 快速排序

    #include<iostream>
    #include<fstream>
    #include<stdio.h>
    #include<iomanip>
    using namespace std;
    void Swap(int &a,int &b)
    {
     int c;
     c=a;
     a=b;
     b=c;
    }
    template<class Type>
    void QuickSort (Type a[], int p, int r,int b[])
    {
          if (p<r)
       {
            int q=Partition(a,p,r,b);
            QuickSort (a,p,q-1,b); //对左半段排序
            QuickSort (a,q+1,r,b); //对右半段排序
           }
    }
    template<class Type>
    int Partition (Type a[], int p, int r,int b[])
    {
     int i=p,j=r+1;
     Type x=a[b[p]];
            // 将< x的元素交换到左边区域
            // 将> x的元素交换到右边区域
            while (true) {
               while (a[b[++i]] <x&&i<r);
               while (a[b[--j]] >x);
               if (i >= j) break;
               Swap(b[i],b[j]);
               }
      Swap(b[p],b[j]);
           return j;
    }
    int main()
    {
     int fanshi;
     int num;
     int i=0;
     while(true)
     {
      cout<<"输入方式:1、手动输入;2、读取文本。"<<endl;
      cin>>fanshi;
      if(fanshi==1)
      {
       cout<<"输入数据的个数:";
       cin>>num;
       float *mm=new float[num];
       int *b=new int[num];
       for(int j=0;j<num;j++)
        b[j]=j;
       for(int g=0;g<num;g++)
       {
        cout<<"输入第"<<g+1<<"个数据:";
        cin>>mm[g];
       }
       cout<<"排序后:\n";
       QuickSort<float>(mm,0,num-1,b);
       for(int k=0;k<num;k++)
       {
        cout<<setw(8)<<mm[b[k]];
        if((k+1)%7==0)
         cout<<endl;
       }
       delete []mm;
       delete []b;
      }
      if(fanshi==2)
      {
       ifstream file("a.txt");
       file>>num;
       float *p=new float[num];
       int *b=new int[num];
       for(int j=0;j<num;j++)
        b[j]=j;
       cout<<"读取txt文件的数据为:\n";
       while(!file.eof())
       {
        if(i<num)
        {
         file>>p[i];
         cout<<setw(8)<<p[i];
         i++;
         if(i%7==0)
          cout<<endl;
        }
       }
       file.close();
       cout<<"\n排序后:\n";
       QuickSort<float>(p,0,num-1,b);
       for(int k=0;k<num;k++)
       {
        cout<<setw(8)<<p[b[k]];
        if((k+1)%7==0)
         cout<<endl;
       }
       delete []p;
       delete []b;
      }
      cout<<"\n跳出或者返回?0、返回;1、退出!"<<endl;
      int m;
      cin>>m;
      if(m==0)
       cout<<endl;
      else
       break;
     }
     return 0;
    }


    文本的数据为:
    14
    19.4
    30.43
    26.88
    7.62
    12.26
    20
    12.13
    5.99
    26.02
    45.55
    22.69
    12.54
    12.7
    21.9 

  • 相关阅读:
    2
    作业5
    实验十
    作业 5 指针应用
    九九乘法表
    实验七(课堂练习)
    实验六 数组 (2)
    实验六 数组
    课堂实验5(求从m到n之间(包括m和n)所有素数的和)
    课堂实验5-2
  • 原文地址:https://www.cnblogs.com/iomango/p/2765638.html
Copyright © 2011-2022 走看看