How to sort and rank a vector in C++ (without using C++11)

前端 未结 5 878
一个人的身影
一个人的身影 2021-01-21 19:07

I am trying to construct a function take takes a vector, ranks it, sorts it and outputs the sorted and ranked vector with the original positioning of the values. For example: I

5条回答
  •  不思量自难忘°
    2021-01-21 19:57

    //Rank the values in a vector
    std::vector rankSort(const std::vector &v_temp)
    {
        vector  v_sort;
        //create a new array with increasing values from 0 to size-1
        for(size_t i = 0; i < v_temp.size(); i++)
            v_sort.push_back(i);
    
        bool swapped = false;
        do
        {
            swapped = false; //it's important to reset swapped
            for(size_t i = 0; i < v_temp.size()-1; i++) // size-2 should be the last, since it is compared to next element (size-1)
                if(v_temp[v_sort[i]] > v_temp[v_sort[i+1]]) 
                {
                    size_t temp = v_sort[i]; // we swap indexing array elements, not original array elements
                    v_sort[i] = v_sort[i+1];
                    v_sort[i+1] = temp;
                    swapped = true;
                }
        }
        while(swapped);
    
        return v_sort;
    }
    

提交回复
热议问题