How to Sort C++ Array in Asc and Desc Mode

How to sort C++ array in ASC and DESC mode?

To sort an array in ascending, use:

#include <algorithm>

int main()
{
// ...
std::sort(array, array+n); // where n is the number of elements you want to sort
}

To sort it in descending, use

#include <algorithm>
#include <functional>

int main()
{
// ...
std::sort(array, array+n, std::greater<int>());
}

How to sort a standard array in descending order - C++ 11

Unlike the raw arrays, std::array won't convert to pointer implicitly (even you can get the pointer explicitly from std::array::data), you should use begin() and end(), which are commonly used to get iterators from STL containers. e.g.

sort(myArray.begin(), myArray.end(), greater<int>());

or

sort(std::begin(myArray), std::end(myArray), greater<int>());

PS: The latter works with raw arrays too.

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

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. Pass another flag to qsort() to change the swap order. So you can pas a bool to indicate it:

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:

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

Change the prototype of qsort() accordingly.

c++ sort(ascending,descending) integer array

You are using Selection Sort. Your program has 4 errors. Use 'if' instead of while.

#include<iostream>
using namespace std;

int main()
{
int i,y,choice,temp,am[5]={8,6,10,7,9};

cout<<"Choice 1 : Descending\nChoice 2 : Ascending\n";
cin>>choice;

if(choice==1)
{
for(i=0;i<5;i++)
{
y=i+1;
while(y<5)
{
if(am[i]<am[y]) //Correction1
{
temp=am[i];
am[i]=am[y];
am[y]=temp;
//y++; //Correction2
}
y++;
}
}
}
else if(choice==2)
{
for(i=0;i<5;i++)
{
y=i+1;
while(y<5)
{
if(am[i]>am[y]) //Correction3
{
temp=am[i];
am[i]=am[y];
am[y]=temp;
//y++; //Correction4
}
y++;
}
}
}
else
cout<<"Error\n";

for(i=0;i<5;i++)
cout<<"am[i]:"<<am[i]<<"\n";

return 0;
}

C++ - Sort array in descending order not working

Based on the example of the reference, what you have should work:

#include <iostream>     // std::cout
#include <algorithm> // std::sort
#include <vector> // std::vector

int main (void) {
int array[6] = {5, 10, 2, 5, 4, 4};
std::sort(array, array + (sizeof array / sizeof array[0]), std::greater<int>());

for (int i = 0; i < 6; ++i)
std::cout << array[i] << " ";
std::cout << '\n';

return 0;
}

Output:

10 5 5 4 4 2

As you can see, this is the same as your code. See it yourself in the Live Demo.

Fastest way to sort an array in descending order

That's a great question. I bet your values array is an array of primitive type!

It's really the sort that is dominant here, because the complexity of Reverse is O(n), while the sort is O(n logn).

The thing is that when sorting primitive types, .NET actually calls a native function, which is extremely fast - much faster that using a Comparison or Comparator.

The function is called TrySZSort:

[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[SecurityCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
private static bool TrySZSort(Array keys, Array items, int left, int right);

and here is how it's called in the Array class:

[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[SecuritySafeCritical]
public static void Sort<T>(T[] array, int index, int length, IComparer<T> comparer)
{
if (array == null)
throw new ArgumentNullException("array");
else if (index < 0 || length < 0)
throw new ArgumentOutOfRangeException(length < 0 ? "length" : "index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
else if (array.Length - index < length)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
else if (length > 1 && (comparer != null && comparer != Comparer<T>.Default || !Array.TrySZSort((Array) array, (Array) null, index, index + length - 1)))
ArraySortHelper<T>.Default.Sort(array, index, length, comparer);
}

Sorting a vector in descending order

With c++14 you can do this:

std::sort(numbers.begin(), numbers.end(), std::greater<>());

How can I make my Quick Sort Algorithm sort the arrays in both Ascending and Descending order?

You can change your Quicksort method to accept an IComparer<T> comparer, and then use that to make the comparisons.

Then you can use Comparer<T>.Default if you want the default comparison order, or you can use Comparer<T>.Create() to create a custom (e.g. reversed) comparison.

Compilable example:

using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
class Program
{
static void Main()
{
int[] data = {6, 7, 2, 3, 8, 1, 9, 0, 5, 4};

QuickSort(data);

Console.WriteLine(string.Join(", ", data)); // Prints 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

QuickSort(data, Comparer<int>.Create((a, b) => b.CompareTo(a)));

Console.WriteLine(string.Join(", ", data)); // Prints 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
}

public static void QuickSort<T>(T[] data)
{
Quick_Sort(data, 0, data.Length - 1, Comparer<T>.Default);
}

public static void QuickSort<T>(T[] data, IComparer<T> comparer)
{
Quick_Sort(data, 0, data.Length - 1, comparer);
}

public static void Quick_Sort<T>(T[] data, int left, int right, IComparer<T> comparer)
{
int i, j;
T pivot, temp;
i = left;
j = right;
pivot = data[(left + right) / 2];
do
{
while ( (comparer.Compare(data[i], pivot) < 0) && (i < right)) i++;
while ( (comparer.Compare(pivot, data[j]) < 0) && (j > left)) j--;
if (i <= j)
{
temp = data[i];
data[i] = data[j];
data[j] = temp;
i++;
j--;
}
} while (i <= j);
if (left < j) Quick_Sort(data, left, j, comparer);
if (i < right) Quick_Sort(data, i, right, comparer);
}
}
}

This has two advantages:

  1. The type T does NOT need to implement IComparable<T>. You can pass in an IComparer<T> object that does the comparison.
  2. You can sort the same data in multiple ways, by passing in different custom IComparer<T> object.

This is the approach adopted by a number of the Linq IEnumerable extensions, for example Enumerable.OrderBy()

Which sorting is efficient to sort data from ascending order to descending order?

In that specific case you don't have to use a sorting algorithm as such. For example you can just swap the ith element with the n - ith element:

for(i = 0; i < size/2; ++i)
{
tmp = arr[i];
arr[i] = arr[size - 1 - i];
arr[size - 1 - i] = tmp;
}

This has always the complexity O(n/2). I dont't think that there is a much faster way. Apart from just reading the data in the other direction of course.



Related Topics



Leave a reply



Submit