codes in highest and lowest in sorting array

Dani AI

Generated

The replies here focus on .NET, which is fine, but the OP tagged C, C++ and Python — so below are practical, language-appropriate ways to get the highest and lowest value without sorting the whole array (sorting is O(n log n); a single scan is O(n) and usually what you want). and pointed out the sort/utility-method route in .NET; for C/C++/Python the common choices are a one-pass scan or, in C++, the library helper that computes both at once.

One-pass (C-style) — initialize min/max from the first element, then walk the array once and update. This is O(n) and needs a check for empty arrays:

/* simple one-pass C */
int find_min_max(int *a, size_t n, int *out_min, int *out_max) {
    if (n == 0) return -1; /* empty array */
    int mn = a[0], mx = a[0];
    for (size_t i = 1; i < n; ++i) {
        if (a[i] < mn) mn = a[i];
        else if (a[i] > mx) mx = a[i];
    }
    *out_min = mn; *out_max = mx;
    return 0;
}

C++ tip — prefer the STL helper std::minmax_element which returns iterators to min and max in a single pass (fewer comparisons than calling min_element and max_element separately):

auto mm = std::minmax_element(v.begin(), v.end());
if (!v.empty()) { auto mn = *mm.first; auto mx = *mm.second; }

Python tip — min() and max() are easy but each does its own pass (2*n). For one-pass use a simple loop:

def min_max(lst):
    it = iter(lst)
    mn = mx = next(it)   # raises StopIteration on empty
    for x in it:
        if x < mn: mn = x
        elif x > mx: mx = x
    return mn, mx

Use sorting only when you need the array ordered. Always handle empty inputs and the element type (ints, floats, custom comparators) appropriately. For reference on Python builtins see the docs for min/max.

Recommended Answers

All 2 Replies

If want to find the highest and lowest VALUE in an array, you could implement the Array.sort method that is available in C#. Here is the example of the Array.sort method in action. Now once you figure out how to implement that method, it will organize the VALUES in ascending order. This means that you can find the smallest value at the first index, and the highest value at the last index.

in .net arrays, you have access to the First and Last methods. They also implement the Max and Min methods which work with any array of number values or values that can be transformed to numbers

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.