• 文件和数组的排序


    #include <iostream>
    #include <fstream>
    #include <vector>
    #include <assert.h>
    using namespace std;
    template <class T>
    void order(vector <T>  &a)
    {
        int count = a.size();
        T temp;
        for (int i=0;i<count;i++)
        {
            for (int j=0;j<count-i-1;j++)
            {
                if (a[j]>a[j+1])
                {
                    temp = a[j];
                    a[j] = a[j+1];
                    a[j+1] = temp;
                }
            }
        }
    }
    template <class T>
    void order(T arr[],int len) 
    {
        T  temp;
        for (int i = 0; i < len - 1; i++)
            for (int j = 0; j < len - 1 - i; j++)
                if (arr[j] > arr[j + 1]) 
                {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
    }
    int main(void)
    {
        //文件排序
        ifstream fin("order.txt");
        assert(fin);
        vector<double> a;    double temp;
        while(!fin.eof())
        {
            fin>>temp;
            a.push_back(temp);
        }
        fin.close();
        order(a);
        ofstream fout("order_out.txt");
        assert(fout);
        for (int i = 0; i<a.size(); i++)
        {
            fout<<a[i]<<endl;
        }
        //数组排序
        double arr[] = { 22, 34, 3,289754282,12313,1231424214};
        int len = (int) sizeof(arr) / sizeof(*arr);
        order(arr,len);
    }

     快速排序法(速度最快)

    #include<iostream>
    using namespace std;
    
    void quickSort(int s[], int l, int r)
    {
        if (l< r)
        {    
            int i = l, j = r, x = s[l];
            while (i < j)
            {    while(i < j && s[j]>= x)     j--; 
            if(i < j)    s[i++] = s[j];
            while(i < j && s[i]< x) i++; 
            if(i < j)     s[j--] = s[i];
            }
            s[i] = x;
            quickSort(s, l, i - 1); 
            quickSort(s, i + 1, r);
        }
    }
    int main()
    {
        int array[]={4,5,12,4,6,5,7,1,3,7};
        int len=sizeof(array)/sizeof(int);
        quickSort(array,0,len-1);
        system("pause");
        return 0;
    }
    View Code
  • 相关阅读:
    LeetCode 面试题32
    LeetCode 102. 二叉树的层序遍历
    LeetCode 面试题32
    LeetCode 面试题32
    LeetCode 面试题31. 栈的压入、弹出序列
    LeetCode 946. 验证栈序列
    LeetCode 50. Pow(x, n)
    LeetCode 572. 另一个树的子树
    LeetCode 面试题50. 第一个只出现一次的字符
    LeetCode 面试题37. 序列化二叉树
  • 原文地址:https://www.cnblogs.com/lwngreat/p/4266460.html
Copyright © 2020-2023  润新知