简体   繁体   English

C ++:按升序排序数组的初始部分,按降序排列另一部分

[英]C++:Sort the initial part of an array in ascending and the other part in descending order

I'm new to C++ and I'm trying to do this : 我是新的C ++,我试图做

I have an array of N elements. 我有一个N元素的数组。 User should be able to input all the elements of an array and a number K . 用户应该能够输入数组的所有元素和数字K. After that I have to sort the array such that the first part (elements 1 to K ) be sorted in ascending mode and the second part (elements K to N ) be sorted in descending mode. 之后,我必须对数组进行排序,使第一部分(元素1K )按升序模式排序,第二部分(元素KN )按降序排序。

Sorting function is implemented by myself. 排序功能由我自己实现。 I can use qsort from cstdlib , but it's not so interesting. 我可以使用cstdlib qsort ,但它不是那么有趣。

I have coded for sorting an array, but I can't understand how to sort an array in two parts. 我已编码排序数组,但我无法理解如何将数组分为两部分。

#include <iostream>
#include <string>

void print_array(int[], int);
void qsort(int[], int, int);

int main()
{
    int array_length;
    int *array, k;
    std::cout << "Write array length: ";
    std::cin >> array_length;
    array = new int[array_length];
    for (int i = 0; i < array_length; i++) {
        std::cout << "Write " << i + 1 << " element: ";
        std::cin >> array[i];
    }
    print_array(array, array_length);
    do {
        std::cout << "Write k: ";
        std::cin >> k;
    } while (k >= array_length);
    qsort(array, 0, k);
    print_array(array, array_length);
}


void print_array(int* array, int length) {
    for (int i = 0; i < length; i++) {
        std::cout << array[i] << "\n";
    }
}

void qsort(int arr[], int fst, int last)
{
    int i, j, pivot, tmp;
    if (fst < last)
    {
        pivot = fst;
        i = fst;
        j = last;
        while (i < j)
        {
            while (arr[i] <= arr[pivot] && i < last)
                i++;
            while (arr[j] > arr[pivot])
                j--;
            if (i < j)
            {
                tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;
            }
        }
        tmp = arr[pivot];
        arr[pivot] = arr[j];
        arr[j] = tmp;
        qsort(arr, fst, j - 1);
        qsort(arr, j + 1, last);
    }
}

You are sorting one half with: 你正在排序一半:

qsort(array, 0, k);

and similarly, you need sort other half: 同样,你需要排序另一半:

qsort(array+k, 0, array_length-k);

Now, the problem is that both parts will be in ascending order. 现在,问题在于两个部分都将按升序排列。 So you need a way to tell qsort() to sort one half in ascending order and the other half in descending order. 因此,您需要一种方法来告诉qsort()按升序排序一半,另一半按降序排序。 Pass another flag to qsort() to change the swap order. 将另一个标志传递给qsort()以更改交换顺序。 So you can pas a bool to indicate it: 所以你可以通过bool表示它:

void qsort(int arr[], int fst, int last, bool pass)
{
           ....
           if (pass && i < j)
            {
                tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;
            }
            if(!pass && i > j) {
                tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;
            }
       ...
       qsort(arr, fst, j - 1, pass); 
       qsort(arr, j + 1, last, pass);

} }

And when you call it you can pass true and false to "switch" the swap order: 当你调用它时,你可以传递truefalse来“切换”交换顺序:

  qsort(array, 0, k, true);
  qsort(array+k, 0, array_length-k, false);

Change the prototype of qsort() accordingly. 相应地更改qsort()的原型。

You just have to replace following lines, in order to get data in decreasing order: 您只需要替换以下行,以便按递减顺序获取数据:

        //while (arr[i] <= arr[pivot] && i < last)
        while (arr[i] >= arr[pivot] && i < last)
            i++;
        //while (arr[j] > arr[pivot])
        while (arr[j] < arr[pivot])

From what I see, your array contains purely integer values which are primitive in nature and can be sorted using c++ sort method. 从我看到的,你的数组包含纯粹的整数值,这些值本质上是原始的,可以使用c ++排序方法进行排序。

#include <algorithm> // this is to access c++ std::sort method

...

std::sort(array + first, array + last) // input range of index of array to be sorted

...

This should take care of it. 这应该照顾它。

Another point to take note is that this sorts in ascending order by default. 需要注意的另一点是默认情况下按升序排序。 So you can play around with CompareTo method and all that. 所以你可以使用CompareTo方法和所有这些。 But my favorite trick is to multiply -1 to all the values in array and sort it and multiply -1 back, ending up with array sorted in descending order. 但我最喜欢的技巧是将-1乘以数组中的所有值并对其进行排序并将-1乘以,最后将数组按降序排序。

The C++ way of writing algorithms for arrays and other sequences of data is through iterators : 为数组和其他数据序列编写算法的C ++方法是通过迭代器

template <typename Iter>
void qsort(Iter begin, Iter end)
{
    auto pivot = begin + (end - begin) / 2;
    std::nth_element(begin, pivot, end);
    qsort(begin, pivot);
    qsort(pivot + 1, end);
}

Combine that with reverse_iterator and we get your desired behavior: 将它与reverse_iterator结合使用,我们得到您想要的行为:

auto lhBegin = array;
auto lhEnd = array + K;
qsort(lhBegin, lhEnd);
// [ 0, 1, ..., K-2, K-1 ] is now in sorted order

auto rhBegin = std::make_reverse_iterator(array + N);
auto rhEnd = std::make_reverse_iterator(array + K);
qsort(rhBegin, rhEnd);
// [ N-1, N-2, ..., K+1, K ] is now in sorted order

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM